简体   繁体   中英

WPF DataGrid does not save changed value to variable

So, I have this little WPF snippet:

<DataGrid x:Name="lstCategories" AutoGenerateColumns="False" Grid.Row="0"
              Margin="5,5,5,5" ScrollViewer.CanContentScroll="True" SelectionMode="Single" CanUserSortColumns="False" CanUserReorderColumns="False">
        <DataGrid.Columns>
            <DataGridTemplateColumn>
                <DataGridTemplateColumn.Header>
                    <DataGridColumnHeader Tag="All" Click="DataGridColumnHeader_Click">All</DataGridColumnHeader>
                </DataGridTemplateColumn.Header>
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <CheckBox IsChecked="{Binding enabled}" />
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
            <DataGridTextColumn Header="Category" Width="Auto" IsReadOnly="True" Binding="{Binding category}" />
        </DataGrid.Columns>
    </DataGrid>

Which displays data as given in:

lstCategories.ItemsSource = categoryList;

Now, when the user clicks the checkbox, I'd expect the datagrid to write this change to categoryListItem.enabled , but when I check the value, it says true no matter what. How can I make the DataGrid store changes to the variable it uses as data source?

Additional Info: I've chosen the TemplateColumn-approach with an embedded checkbox because this way the user does not have to click two times to modify the check box.

Update 1: I've updated the XAML to incorporate TwoWay-Binding as:

<CheckBox IsChecked="{Binding enabled, Mode=TwoWay}"/>

The data source variable still does not get updated.

I see you've already figured out Mode=TwoWay (which isn't necessary anyway, as it is the default if you don't explicitly set it). Now all you have to do is set UpdateSourceTrigger to PropertyChanged .

<DataTemplate>
    <CheckBox IsChecked="{Binding enabled, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
</DataTemplate>

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