c# - 选择组合框项目时 DataTrigger 不起作用
问题描述
我有一个要动态填充的组合框。
当用户从组合框中选择一个项目时,需要显示一个标签。
这在我使用静态组合框时有效,但当组合框是动态时则无效。我很确定它与Name
组合框项目的字段有关。
这是代码:
C#:
public ObservableCollection<ComboBoxItem> cbItems { get; set; }
public ComboBoxItem SelectedcbItem { get; set; }
public MainWindow()
{
InitializeComponent();
this.DataContext = this;
cbItems = new ObservableCollection<ComboBoxItem>();
var cbItem = new ComboBoxItem { Content = "<--Select-->"};
SelectedcbItem = cbItem;
cbItems.Add(cbItem);
var cbItem1 = new ComboBoxItem();
cbItem1.Content = "Option 1";
cbItem1.Name = "iOne";
var cbItem2 = new ComboBoxItem();
cbItem2.Content = "Option 2";
cbItem2.Name = "iTwo";
cbItems.Add(cbItem1);
cbItems.Add(cbItem2);
}
XAML:
<ComboBox Width="130" ItemsSource="{Binding cbItems}" SelectedItem="{Binding SelectedcbItem}" Grid.Column="0" Grid.Row="4" Grid.ColumnSpan="2" VerticalAlignment="Bottom" HorizontalContentAlignment="Center"/>
<Label Content="One is shown" Grid.Column="0" Grid.Row="6">
<Label.Style>
<Style TargetType="Label">
<Setter Property="Visibility" Value="Hidden" />
<Style.Triggers>
<DataTrigger Binding="{Binding ElementName=iOne, Path=IsSelected}" Value="True">
<Setter Property="Visibility" Value="Visible"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Label.Style>
</Label>
解决方案
使用此 XAML
<ComboBox x:Name="cb"
ItemsSource="{Binding CbItems}" SelectedItem="{Binding SelectedCbItem}" .../>
<Label Content="One is shown" ...>
<Label.Style>
<Style TargetType="Label">
<Setter Property="Visibility" Value="Hidden" />
<Style.Triggers>
<DataTrigger Binding="{Binding ElementName=cb, Path=SelectedItem}"
Value="Option 1">
<Setter Property="Visibility" Value="Visible"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Label.Style>
</Label>
后面有这段代码:
public List<string> CbItems { get; }
public string SelectedCbItem { get; set; }
public MainWindow()
{
InitializeComponent();
cbItems = new List<string> { "Option 1", "Option 2" };
DataContext = this;
}
或者:
<DataTrigger Binding="{Binding ElementName=cb, Path=SelectedIndex}" Value="0">
如果您想让 DataTrigger 使用 Binding 到源属性SelectedCbItem
,例如
<DataTrigger Binding="{Binding SelectedCbItem}" Value="Option 1">
该属性必须触发属性更改通知,例如 INotifyPropertyChanged 接口的 PropertyChanged 事件。
推荐阅读
- javascript - FB.ui 未定义
- svn - git pull-remote 分支找不到远程参考 [尝试了许多解决方案但失败]
- python - selenium.common.exceptions.TimeoutException 同时通过 expected_conditions 在元素上调用 .click()
- java - 利用 spring kafka 在 kafka 消费者中手动提交偏移的方法
- python - 训练后的神经网络步骤
- python - 按索引访问枚举中的项目
- php - 在两个单词之间执行两个空格
- python - 表单中字段之间的Django间距
- mysql - 从每个组中获取除最大值之外的所有项目 - mysql
- kubernetes - 与 ConfigMap 相比,Secrets 的价值是多少