首页 > 解决方案 > 选择组合框项目时 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>

标签: c#wpf

解决方案


使用此 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 事件。


推荐阅读