我想通过使用DataTrigger将ComboBox的SelectedIndex设置为0,当它绑定的SelectedItem为null时。但它没有用。我哪里错了?
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仍无法正常工作!
我的要求很简单,当在组合框中没有选择任何内容时,我想要选择第一个项目。
答案 0 :(得分:1)
这只是一个猜测但是当你同时使用SelectedItem
和SelectedIndex
时,你会创建对WPF实现的依赖:“谁赢了?”是一个实现的东西。即使它在某处记录,也意味着每个开发人员都知道订单(这也不好,因为你永远不知道谁将维护你的代码)。
我认为您在这里可以做的最简单的事情是使用对ViewModel
的{{1}}属性的单一绑定,并让SelectedColorIndex
根据ViewModel
计算值。所以最终结果将如下所示:
color_master
更新:由于您说您的视图模型无法触及,因此这是另一种选择。编写自己的IValueConverter,它将采用<ComboBox SelectedIndex="{Binding MyObjectViewModel.SelectedColorIndex, Mode=TwoWay}"
ItemsSource="{Binding MyEntities.color_master}"
DislayMemberPath="COLOR_DESCRIPTION" >
</ComboBox>
并将其转换为索引:
MyObject.color_master
<ComboBox SelectedIndex="{Binding MyObject.color_master, Mode=TwoWay, Converter={StaticResouce ColorMasterToIndexConverter}}"
ItemsSource="{Binding MyEntities.color_master}"
DislayMemberPath="COLOR_DESCRIPTION" >
</ComboBox>
在可到达的资源中定义{例如,在同一个ColorMasterToIndexConverter
集合中)。