WPF绑定DataGridCheckBoxColumn未更新

8

我正试图弄清如何正确处理DataGridCheckBoxColumn。 我有一个包括“发布”选项的数据列表。 当选中时,对象将被标记为要发布到另一台服务器。 目前为止,这就是我所拥有的:

<DataGrid x:Name="grdEducationalPopups" 
              HorizontalAlignment="Left" VerticalAlignment="Top"
              Margin="19,155,0,0"                   
              AlternationCount="2"
              AutoGenerateColumns="False"
              ItemsSource="{Binding PopupCollection}"
              Loaded="grdEducationalPopups_Loaded"
              MinRowHeight="26"
              RowDetailsTemplate="{StaticResource RowDetailTemplate}" RowDetailsVisibilityChanged="grdEducationalPopups_RowDetailsVisibilityChanged" SelectionChanged="grdEducationalPopups_SelectionChanged" Grid.ColumnSpan="2">           
        <DataGrid.RowHeaderTemplate>
            <DataTemplate>
                <ToggleButton x:Name="RowHeaderToggleButton" Click="ToggleButton_Click" Cursor="Hand"/>                    
            </DataTemplate>
        </DataGrid.RowHeaderTemplate>
        <DataGrid.Columns>                
            <DataGridTextColumn Width="150" Binding="{Binding DisplayName}" Header="Form Name" IsReadOnly="True"/>
            <DataGridTextColumn Width="280" Binding="{Binding URLLocation}" Header="Page Address"/>
            <DataGridTextColumn Width="125" Binding="{Binding DateLastTouched}" Header="Date Modified" IsReadOnly="True"/>
            <DataGridTextColumn Width="125" Binding="{Binding DateRowAdded}" Header="Date Added" IsReadOnly="True"/>
            <DataGridCheckBoxColumn Header="Publish" Binding="{Binding Path=Publish}">
                <DataGridCheckBoxColumn.CellStyle>
                    <Style>
                        <EventSetter Event="CheckBox.Checked" Handler="OnChecked"/>
                    </Style>
                </DataGridCheckBoxColumn.CellStyle>
            </DataGridCheckBoxColumn>
        </DataGrid.Columns>
    </DataGrid>

我现在有一个 OnClick 的代码,但是它目前除了允许我检查值之外没有起到任何作用。我的列表中的发布值没有改变。给定记录的发布值仍然为 false,而应该是 true。 如果我将默认值从 false 更改为 true 并启动我的应用程序,则所有复选框都会被选中,这是我所期望的。这告诉我我的绑定是正确的。

如何正确地管理用户更改,以便我可以适当地对更改进行操作?在我的代码后台,我获得一个 DataGridCell 对象并可以从那里确定行数据,然后我可以编辑该数据。但我认为绑定数据应该处理这个问题。


假设您的“发布”选项是一个布尔属性,您应该在PropertyChangeEvent中对该属性的更改做出反应,而不是使用OnChecked事件。为您的PopupCollection项目设置PropertyChange监听器,例如在ViewModel或任何需要它的地方。如果事件触发并且属性名称为“Publish”,则可以执行相应的发布操作。 - tabina
感谢所有的回复。我的问题核心在于我没有正确地实现数据绑定。我有一个代码后台方法,在运行时设置项目源,而我的实现方式是问题的核心。 - Daniel Lee
2个回答

14

你的代码没有问题,只是该值不会立即更新,只有在 ComboBox 失去焦点后才会更新。

你可以通过在绑定上设置 UpdateSourceTrigger=PropertyChanged 来改变这一点。

<DataGridCheckBoxColumn Header="Publish" Binding="{Binding Path=Publish, UpdateSourceTrigger=PropertyChanged}">

0

我宁愿不使用bode,而是在ViewModel中管理它。我现在还没有执行你的代码,但首先,我会像这样配置CheckBoxColumn的绑定:

Binding="{Binding Path=Publish, Mode=TwoWay}"

在 Publish 属性的 setter 中,您可以编写业务逻辑。如果它非常耗时(通常需要访问网络),我建议异步执行。
如果您需要,我可以提供一个简单的示例。但是其他帖子中应该已经有很多了。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接