1

Im new in wpf programming and i have an application with MVVM. I have a StackPanel and inside the StackPanel there is a ItemsControl named ListView and the Itemsource is my ObserveCollection NewProducts which conatins ProductID and Name.

So what is my code does, well it generates buttons with Names from my Collection NewProducts and i wanna give this buttons Command that triggers when i click on them.

I try this:

<StackPanel Grid.Row="1">
    <ItemsControl x:Name="ListViewProducts" ItemsSource="{Binding NewProducts}">
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <Border Margin="10" Width="auto" Height="auto">
                    <StackPanel>
                        <Border Width="100" Height="40" CornerRadius="5">
                            
                            <Button Content="{Binding Name}" Tag="{Binding ProductId}" FontWeight="Bold" Command="{BindingSaleViewModel.SendCommand}"/>
                            
                        </Border>
                       
                    </StackPanel>
                </Border>
            </DataTemplate>
         
        </ItemsControl.ItemTemplate>
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <WrapPanel/>
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
    </ItemsControl>
</StackPanel>

But when i run my program and when i click on my buttons nothing happens. Its because the Command that i have in my SaleViewModel was not found in Product which is my Model class. And i wanna know if i can somehow get the path to my Command in my ViewModel.

Thanks, and please forgive me mine English, I know its bad.

Ackdari
  • 3,222
  • 1
  • 16
  • 33
Hanz Cz
  • 19
  • 1

2 Answers2

0

Binding methods in WPF is unfortunately not that simple. The command is actually a class, that implements the ICommand interface.

You can find an example here: How to Bind a Command in WPF.

Otherwise you can bind the click event to a method in code-behind <Button Click="Button_Click"/> In code-behind:

private void Button_Click(object sender, RoutedEventArgs e)
{
    // Add your code here...
}
Dharman
  • 30,962
  • 25
  • 85
  • 135
Claus H
  • 194
  • 5
0

Give your root element a name. eg:

<UserControl x:Class="blah" 
             other stuff
             x:Name="root">

Then you can reference the root element in your binding, who's datacontext will (presumably?) be your SaleViewModel:

<Button Content="{Binding Name}" Tag="{Binding ProductId}" FontWeight="Bold" 
        Command="{Binding DataContext.SendCommand, ElementName=root}"
        CommandParameter="{Binding}"/>

Also note the CommandParameter binding which will pass the button's data context (Product) through to your command, otherwise you won't know which product the command relates to.

GazTheDestroyer
  • 20,722
  • 9
  • 70
  • 103