简体   繁体   中英

Bind Object from Button to Property in ViewModel WPF

what I a trying to do here is bind the object that the button contains to a property in my ViewModel in order to use it, but cannot resolve my problem. I read about Tag property but couldn't fully understand how it binds and how can I use it.

My Buttons:

<DataTemplate x:Key="Template">
        <GroupBox>
            <WrapPanel>
                <Button x:Name="Button"
                        FontSize="10"
                        Height="80" Width="80"
                        Content="{Binding Name}"
                </Button>
           </WrapPanel>
        </GroupBox>
    </DataTemplate>

I populate my buttons with data from ObservableCollection

<WrapPanel x:Name="OrderButtons"
               VerticalAlignment="Bottom">
        <ScrollViewer x:Name="OrderButtons1"
                  Margin="3">
            <ItemsControl   
                            ItemTemplate="{StaticResource OrderTemplate}"
                            ItemsSource="{Binding Source={StaticResource ObservableCollectionWithData}}">
                <ItemsControl.ItemsPanel>
                    <ItemsPanelTemplate>
                        <WrapPanel Orientation="Horizontal">
                        </WrapPanel>
                    </ItemsPanelTemplate>
                </ItemsControl.ItemsPanel>
            </ItemsControl>
        </ScrollViewer>
    </WrapPanel>

My ViewModel

public class OrderViewModel : ObservableCollection<Order>
{
    public Item OrderItem{ get; set; }

    public OrderViewModel()
    {
    }
}

What should I do in order to bind my Button, which contains object from type Item(my custom class) to OrderItem property of the my ViewModel?

What I tried is:

  <Button x:Name="OrderButton"
                        FontSize="10"
                        Height="80" Width="80"
                        Content="{Binding Name}"
                        Tag="{Binding OrderItem, Source={StaticResource OrderViewModel}}"
                </Button>

Looks to me like you're creating a 'selector'; ie when the button is clicked, you want the OrderItem property of the view model to contain the 'Item' that was clicked.

If this is the case, you'd be better off using a ListBox as follows:

<ListBox ItemsSource="{Binding Source={StaticResource ObservableCollectionWithData}}" SelectedItem="{Binding OrderItem, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
  <ListBox.ItemTemplate>
    <DataTemplate>
      <TextBlock Text="{Binding Name}"/>
    </DataTemplate>
  </ListBox.ItemTemplate>
</ListBox>

You should also then implement INotifyPropertyChanged in your ViewModel.

Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM