简体   繁体   中英

Getting Checked property from CheckBox when Command is called in WPF

I have a grid of CheckBoxes in a WPF C# project. Each CheckBox's Command property is bound to a CheckBoxChangedCommand in my WView.xaml file, like so:

<CheckBox Grid.Row="0" IsChecked="true" x:Name ="CheckBox0" 
          Command="{Binding CheckBoxChangedCommand}" />
<CheckBox Grid.Row="1" IsChecked="true" x:Name="CheckBox1" 
          Command="{Binding CheckBoxChangedCommand}" />

Each time one of the CheckBoxes is either checked or unchecked, I call CheckBoxChanged . How would I go about displaying a pop-up window showing either 1. the row number in the grid of the CheckBox and the name of the CheckBox ("CheckBox0", for example) and 2. The Checked value (true/false) for the checkbox?

My CheckBoxChangedCommand, in WViewModel.cs file, looks like this:

public ICommand CheckBoxChangedCommand
{
    get
    {
        return new RelayCommand(param =>
        {
            MessageBox.Show("CheckBoxChanged!"); 
        });
    }
}

How can I access the IsChecked property and the row number of the CheckBox that triggered CheckBoxChanged from within CheckBoxChanged ? How can I pass the data from my View to my ViewModel?

You definitely need to do more with binding here.

First of all, you should probably be binding the IsChecked property of your Checkboxes to a property on your viewmodel.

Second, based on your comment about needing to know the row number of the checkbox that was checked, I'd say you probably need to be generating the "row" including the CheckBox via databinding, so that you can then pass the object that represents the row as the CommandParameter to your CheckBoxChangedCommand.

So something like:

<ListBox ItemsSource="{Binding MyItems}" />

and then in your resources:

<DataTemplate DataType="{x:Type local:MyItemType}">
    <CheckBox IsChecked="{Binding IsChecked}" 
              Command="{Binding CheckChangedCommand}" 
              CommandParameter="{Binding}" />
</DataTemplate>

Note: Your CheckChangedCommand is probably on the main ViewModel, not the item-level ViewModel, so you probably need to do some other type of lookup to make it find it - this example is just for simplicity

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