wpf 4.0 datagrid template column two-way binding problem

前端 未结 2 1793
野的像风
野的像风 2021-01-01 19:49

I\'m using the datagrid from wpf 4.0. This has a TemplateColumn containing a checkbox. The IsChecked property of the checkbox is set via binding.

The problem is tha

相关标签:
2条回答
  • 2021-01-01 20:27

    Here's the deal, the way the data grid works, is that it creates a data view and displays it instead of the original data, therefore when you simply bind a property in the CellTemplate it doesn't get propagated from the view to the data.

    What you need to do is use the CellEditingTemplate so that the data grid knows when you're editing, and can propagate it to the data when done (or it can undo it if you cancel).

    Here's the modified XAML for you:

    <Window.Resources>
        <DataTemplate x:Key="IsSelectedColumnTemplate">
            <TextBlock Text="{Binding IsSelected}"/>
        </DataTemplate>
        <DataTemplate x:Key="IsSelectedColumnTemplateEditing">
            <CheckBox IsChecked="{Binding Path=IsSelected, Mode=TwoWay}"/>
        </DataTemplate>
    </Window.Resources>
    
    ...
    <DataGridTemplateColumn 
        Header="Preselected"
        x:Name="myIsSelectedColumn" 
        CellTemplate="{StaticResource IsSelectedColumnTemplate}"
        CellEditingTemplate="{StaticResource IsSelectedColumnTemplateEditing}"
        CanUserSort="True"
        Width="Auto"
    />
    ...
    
    0 讨论(0)
  • 2021-01-01 20:31

    You set UpdateSourceTrigger=PropertyChanged in your Checkbox IsChecked binding in the datatemplate: <CheckBox IsChecked="{Binding Path=IsSelected, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />

    0 讨论(0)
提交回复
热议问题