wpf - 在 DataGrid 中绑定(bind) TextBlock 文本和 ComboBox SelectionChanged 事件时遇到问题

标签 wpf mvvm binding combobox textblock

我的问题是我似乎无法将选择更改事件从 ComboBox 编辑计时到 TextBlock 更新。一切都显示属性,但是当我在后面的代码中的 SelectionChanged 事件中获取 Grade 时,它​​不会更新为实际值。要获得实际值,我必须更改 ComboBox 上的选择,然后单击我正在编辑的数据网格的行。然后,当我选择一个新等级时,它会更新以显示最后一个等级被选中。因此,即使它看起来应该全部连接,但在我单击它之前,该行实际上并没有更新,而不是当我做出不同的 ComboBox 选择时。那么有没有办法改变数据网格更新数据的方式以与组合框保持同步?任何帮助表示赞赏。谢谢。

<DataGridTemplateColumn Header="Grade" CellStyle="{StaticResource StarNumberCellStyle}">
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Grade}" Margin="3,1,3,1">
            </TextBlock>
        </DataTemplate>
     </DataGridTemplateColumn.CellTemplate>
     <DataGridTemplateColumn.CellEditingTemplate>
         <DataTemplate>
             <ComboBox ItemsSource="{Binding DataContext.Grades, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGrid}}}" 
                 SelectedItem="{Binding Grade,Mode=TwoWay, NotifyOnTargetUpdated=True}" Tag="{Binding}" ComboBox.IsTextSearchEnabled = "True">
                 <i:Interaction.Triggers>
                     <i:EventTrigger EventName="SelectionChanged">
                         <i:InvokeCommandAction Command="{Binding DataContext.GradeSelectCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGrid}}}" 
                               CommandParameter ="{Binding}"/>
                     </i:EventTrigger>
                 </i:Interaction.Triggers>
             </ComboBox>
         </DataTemplate>
     </DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>

最佳答案

请参阅我对 DataGridTemplateColumn 的回答此处注意事项:DataGrid and Observable Collection in WPF

简而言之,这应该适合你( UpdateSourceTrigger=PropertyChanged ):

<ComboBox ... 
          SelectedItem="{Binding Grade, UpdateSourceTrigger=PropertyChanged, 
                                 Mode=TwoWay, NotifyOnTargetUpdated=True}"
          ... >

关于wpf - 在 DataGrid 中绑定(bind) TextBlock 文本和 ComboBox SelectionChanged 事件时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16800457/

相关文章:

wpf - WPF 应用程序中的 XamlParseException - 但仅当安装在 XP 上时才会出现

c# - 不同类中的命令定义

iphone - 让 TestFlight 与 Monotouch 应用程序配合使用时出现问题

c# - WPFToolkit 数据网格 : Highlight modified rows

c# - 在 Caliburn Micro 中使用 Telerik RadWindow 和自定义 WindowManager 的问题

mvvm - 我的用户控件和 ViewModel 之间的绑定(bind)

c# - MVVM 设计模式的基本指导要求

.net - 如何从 MVVM 调用 Winforms 风格的 Invoke/Delegate?

c# - WPF TreeView 绑定(bind)多个子集合

c# - 如果从 pendrive 或服务器执行 Entity Framework 失败