WPF ComboBox选中项变更时Unit属性未更新问题求助
解决WPF ComboBox选中项变更时未更新绑定属性的问题
这问题我熟!核心原因是你没设置绑定的更新触发时机——WPF里ComboBox.Text的绑定默认是在控件失去焦点(LostFocus)时才会把值同步到绑定的属性,所以你点选项切换时Unit属性没反应,只有Tab离开才触发更新。
只需要给两个ComboBox的Text绑定加上UpdateSourceTrigger=PropertyChanged就行,修改后的代码如下:
<DataGridTemplateColumn x:Name="UnitConcue"> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <ComboBox ItemsSource="{Binding Source={x:Static ene:Sysleton.UnitValues}}" Text="{Binding Unit, UpdateSourceTrigger=PropertyChanged}" HorizontalContentAlignment="Stretch"/> </DataTemplate> </DataGridTemplateColumn.CellTemplate> <DataGridTemplateColumn.CellEditingTemplate > <DataTemplate> <ComboBox ItemsSource="{Binding Source={x:Static ene:Sysleton.UnitValues}}" Text="{Binding Unit, UpdateSourceTrigger=PropertyChanged}"/> </DataTemplate> </DataGridTemplateColumn.CellEditingTemplate> </DataGridTemplateColumn>
解释一下:
UpdateSourceTrigger=PropertyChanged会让绑定源(也就是你的Unit属性)在ComboBox.Text值一发生变化就立刻更新,不管控件有没有失去焦点。- 不管是
CellTemplate(普通显示状态)还是CellEditingTemplate(编辑状态)的ComboBox,都需要加上这个设置,确保两种状态下选中选项都能实时同步属性。
如果你的场景是绑定选中项而非文本,也可以用SelectedItem绑定并同样设置UpdateSourceTrigger=PropertyChanged,不过看你的代码用的是Text,上面的修改就完全能解决问题啦。
内容的提问来源于stack exchange,提问作者bobsyauncle
相关产品推荐
相关产品推荐

