Reputation: 417
I have a combo box that is to be filled dynamically.
When the user selects an item from the combo box, a label needs to show up.
This works when I use a static combo box, but when the combo box is dynamic it does not. I'm pretty sure it has to do with the Name
field of the combo box item.
Here is the code :
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>
Upvotes: 0
Views: 529
Reputation: 128062
Use this 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>
with this code behind:
public List<string> CbItems { get; }
public string SelectedCbItem { get; set; }
public MainWindow()
{
InitializeComponent();
cbItems = new List<string> { "Option 1", "Option 2" };
DataContext = this;
}
Alternatively:
<DataTrigger Binding="{Binding ElementName=cb, Path=SelectedIndex}" Value="0">
If you want to make the DataTrigger use a Binding to the source property SelectedCbItem
, like
<DataTrigger Binding="{Binding SelectedCbItem}" Value="Option 1">
that property must fire a property change notification, e.g. the PropertyChanged event of the INotifyPropertyChanged interface.
Upvotes: 2