选择组合框项目时,DataTrigger不起作用

时间:2019-07-03 10:56:56

标签: c# wpf

我有一个可以动态填充的组合框。

当用户从组合框中选择一个项目时,需要显示一个标签。

当我使用静态组合框时此方法有效,但是当组合框为动态组合框时则无效。我很确定这与组合框项目的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>

1 个答案:

答案 0 :(得分:2)

使用此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使用对源属性SelectedCbItem的绑定,例如

<DataTrigger Binding="{Binding SelectedCbItem}" Value="Option 1">

该属性必须触发属性更改通知,例如INotifyPropertyChanged接口的PropertyChanged事件。