Joseph Devlin
Joseph Devlin

Reputation: 1800

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 these 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.

Upvotes: 0

Views: 530

Answers (1)

Kent Boogaart
Kent Boogaart

Reputation: 178790

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.

Upvotes: 2

Related Questions