简体   繁体   中英

How to make event handler with WPF Datagrid checkbox?

<DataGrid x:Name="MappingDataGrid">
    <DataGrid.Columns>
        <DataGridCheckBoxColumn Header="Included" Binding="{Binding Path=IsIncluded}"></DataGridCheckBoxColumn>
        <DataGridTextColumn Header="From" Binding="{Binding Path=KeyString}"></DataGridTextColumn>
        <DataGridTextColumn Header="To" Binding="{Binding Path=ValueString}"></DataGridTextColumn>
    </DataGrid.Columns>

I want to make Datagrid with Checkbox, the binding data is on MainWindow's member and I want to use a checkbox when I checked the box the binded object be changed. However, I tried to find an event and event handler but I cannot find that.

you need to add event handler in the ViewModel

example:

  public event PropertyChangedEventHandler PropertyChanged;
    private void OnPropertyChanged(string property)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(property));
    }

and add the event to the member in the ViewModel

        private string isIncluded;
    public string IsIncluded
    {
        get { return isIncluded; }
        set
        {
            isIncluded = value;
            OnPropertyChanged("IsIncluded");
        }
    }

and then in the xmal.cs you need to contact the Binding to the ViewModel

public partial class Mapping: Window
{
    private readonly ViewModel viewModel = new ViewModel();
    public ViewModel ()
    {
        InitializeComponent();
        DataContext = viewModel ;
    }
}

and add in the xmal after the binding the event

<DataGrid x:Name="MappingDataGrid">
<DataGrid.Columns>
    <DataGridCheckBoxColumn Header="Included" Binding="{Binding Path=IsIncluded,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"></DataGridCheckBoxColumn>
    <DataGridTextColumn Header="From" Binding="{Binding Path=KeyString}"></DataGridTextColumn>
    <DataGridTextColumn Header="To" Binding="{Binding Path=ValueString}"></DataGridTextColumn>
</DataGrid.Columns>

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