Reputation: 43
There are some posts that might point to my problem, but then again I get stuck by other problems when I try to apply their solution to my task.
So, I want a ComboBox to show a number (PathID) from my Path-class. Path has a property called PathState, which is an enum that can be PathState.red, PathState.blue, PathState.green, indicating a color.
I'd like to create a simple hardcoded list of type Path, just for learning, and then populate the ComboBox. I'd like to create three Path-objects with increasing ID, giving each a distinct color by asigning the PathState property.
By starting the app, the ComboBox should consist of the numbers 1, 2, and 3, whereas 1 is red, 2 is green, 3 is blue.
I know I need to get to it via ComboBox.ItemTemplate, DataTemplate, and DataTrigger - I just don't know where to start.
public class Path
{
public int PathID {get;set;}
public PathState PathState { get; set;}
}
public enum PathState
{
red = 0,
green = 1,
blue = 2
}
EDIT: OK, I've made some effort, but are stuck on the DataTrigger-Part: here is my code:
<ComboBox Name="cmbTest" ItemsSource="{Binding MyPaths}" Grid.Column="1" Grid.Row="1" VerticalContentAlignment="Center" HorizontalContentAlignment="Center">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock x:Name="cmbText" Text="{Binding PathId}" Foreground="Red"/>
</DataTemplate>
</ComboBox.ItemTemplate>
<Style>
<Style.Triggers>
<DataTrigger Binding="{Binding Path=MyPaths}" Value="MyPaths.PathState">
<!-- Actually, I don't know how to continue beyond this point) -->
</DataTrigger>
</Style.Triggers>
</Style>
</ComboBox>
Upvotes: 2
Views: 358
Reputation: 13438
You should write a IValueConverter
that converts from your PathState
to the corresponding System.Windows.Media.Brush
. Use predefined Brushes
(https://learn.microsoft.com/de-de/dotnet/api/system.windows.media.brushes?view=netframework-4.8) unless you need something special.
Then instantiate the value converter somewhere in your resources (could be at any parent level, I put it in ComboBox
only for this example. Then use the converter to bind your color to display properties.
If you want the Background
, do it within ItemContainerStyle
. If you want Foreground
put it wherever its needed. Beware: my example puts Foreground=Background, you won't see much.
<ComboBox>
<ComboBox.Resources>
<local:MyColorConverter x:Key="colorConverter"/>
</ComboBox.Resources>
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding PathID}" Foreground="{Binding PathState,Converter={StaticResource colorConverter}}"/>
</DataTemplate>
</ComboBox.ItemTemplate>
<ComboBox.ItemContainerStyle>
<Style TargetType="ComboBoxItem">
<Setter Property="Background" Value="{Binding PathState,Converter={StaticResource colorConverter}}"/>
</Style>
</ComboBox.ItemContainerStyle>
</ComboBox>
Upvotes: 1