开发者

Problem when setting up command bindings in XAML

I am trying to create a menu bar for my application. I have created a collection in xaml that I will contain menu items that my menu will bind to.

In xaml I have created an array that I use as my static resource for binding.

<coll:ArrayList x:Key="MenuOptionsList">
        <model:DashboardMenuBarItem 
               Icon="the location of an image in my images folder" 
               DisplayName="The test that will appear under my button"  
               CommandName="someCommandInMyViewModel"/>
</coll:ArrayList>

I am using a listbox with a data template to show t开发者_运维技巧hese items as follows.

<ListBox x:Name="lstNavigateTo" MinWidth="400" DockPanel.Dock="Top"
             ItemsSource="{Binding Source={StaticResource MenuOptionsList}}" 
             ScrollViewer.HorizontalScrollBarVisibility="Disabled"
             Style="{StaticResource horizontalListTemplate}">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Margin="5">
                    <Button Height="60" Width="60"
                            Command="{Binding Mode=OneWay, Path=CommandName}">
                        <Button.Content>
                            <Image Source="{Binding Path=Icon}" Grid.Row="0" />
                        </Button.Content>
                    </Button>
                    <TextBlock Text="{Binding Path=DisplayName}" 
                               Width="100" TextAlignment="Center" Grid.Row="1" />
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
</ListBox>

My problem is that I am using the MVVM design pattern and cannot get the command bindings to work on the button click. Previously I would have managed the button click like this.

Command="{Binding someCommandInMyViewModel}"

That would work fine but when I try to bind a command to a property of an item in my collection the command will not fire.

Does anyone know how I can achieve this.


The CommandName property in your collection is of type String, whereas the Command property on Button is of type ICommand. In what way are you expecting WPF to resolve an ICommand from a String? You'll need to help it: either create a converter and use it in your binding, or change your CommandName property so that it contains an actual ICommand rather than a String.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜