WPF 数据触发器不起作用 - 组合框选定的索引未设置为 0
我想通过使用 DataTrigger 将 ComboBox 绑定的 SelectedItem 为 null 时将 ComboBox 的 SelectedIndex 设置为 0。但它不起作用。我哪里出错了?
xaml如下:
<ComboBox SelectedItem="{Binding MyObject.color_master, Mode=TwoWay}"
ItemsSource="{Binding MyEntities.color_master}"
DislayMemberPath="COLOR_DESCRIPTION" >
<ComboBox.Style>
<Style TargetType="ComboBox">
<Style.Triggers>
<DataTrigger Binding="{Binding Path=MyObject.color_master}" Value="{x:Null}">
<Setter Property="SelectedIndex" Value="0" />
</DataTrigger>
</Style.Triggers>
</Style>
</ComboBox.Style>
</ComboBox>
这里MyObject.color_master为null,但DataTrigger仍然无法工作!
我的要求很简单,当组合框中没有选择任何内容时,我希望选择第一项。
I want to set the SelectedIndex of ComboBox to 0 when the SelectedItem it is bound to is null by using DataTrigger. But it is not working. Where am I going wrong?
The xaml is as follows:
<ComboBox SelectedItem="{Binding MyObject.color_master, Mode=TwoWay}"
ItemsSource="{Binding MyEntities.color_master}"
DislayMemberPath="COLOR_DESCRIPTION" >
<ComboBox.Style>
<Style TargetType="ComboBox">
<Style.Triggers>
<DataTrigger Binding="{Binding Path=MyObject.color_master}" Value="{x:Null}">
<Setter Property="SelectedIndex" Value="0" />
</DataTrigger>
</Style.Triggers>
</Style>
</ComboBox.Style>
</ComboBox>
Here MyObject.color_master is null, but still the DataTrigger is not working !
My requirement is very simple, when nothing is selected in combobox, I want the first item to be selected.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这只是一个猜测,但当您同时使用
SelectedItem
和SelectedIndex
时,您会创建对 WPF 实现的依赖:“谁赢了?”是一个执行的事情。即使它记录在某处,也意味着每个开发人员都知道该顺序(这也不好,因为您永远不确定谁将维护您的代码)。我认为您在这里可以做的最简单的事情是使用对
ViewModel
的SelectedColorIndex
属性的单个绑定,并让ViewModel
根据color_master
。因此最终结果将如下所示:更新:既然你说你的视图模型不能被触及,那么这里有另一个选择。编写您自己的 IValueConverter,它将采用
MyObject.color_master
并将其转换为索引:其中
ColorMasterToIndexConverter
在可访问的资源字典中定义(例如,在同一个中) UserControl.Resources
集合)。It's only a guess but when you use both
SelectedItem
andSelectedIndex
you create dependency on WPF implementation: "who wins?" is an implementation thing. Even if it's documented somewhere it would imply that every developer knows the order (which is not good too, because you never sure who will maintain your code).I think the simplest thing you can do here is use a single binding to
ViewModel
'sSelectedColorIndex
property and let theViewModel
calculate the value based oncolor_master
. So the end result will look like this:Update: Since you said your view model can't be touched, here is another option. Write your own IValueConverter which will take an
MyObject.color_master
and convert it to the index:Where
ColorMasterToIndexConverter
defined in a reachable resource dictonary (for say, in the sameUserControl.Resources
collection).