Im struggling with a problem that might seem easy first: I want to display some grid with different colors. I have a listview that is binded to a list. The list containst Colors (i have tried SolidColorBrush as well). The listview can display the elements, so in the current case you can see 1 grid per item. I want to bind the background of the grid (so the datatemplate) to the color property itself. For example: lets say i have a white and black color in my list. Then i want to display a black and a white grid using listview. However, i cannot bind the background to anything, the binding always fails and I couldnt find a solution.
Here is the xaml code:
<ListView ItemsSource="{Binding lightColors}" Height="30" HorizontalAlignment="Left">
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Setter Property="Margin" Value="5"></Setter>
<Setter Property="Background" Value="{Binding **WHAT TO WRITE HERE?**}"></Setter>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListViewItem">
<Grid Height="30" Width="30"></Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ListView.ItemContainerStyle>
<ListView.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel>
</WrapPanel>
</ItemsPanelTemplate>
</ListView.ItemsPanel>
<ListView.ItemTemplate>
<DataTemplate>
</DataTemplate>
</ListView.ItemTemplate>
And some code snippets:
public List<Color> lightColors { get; set; }
public void fillLightColors()
{
Color myColor = Color.FromRgb(100, 150, 75);
LightColor.Add(myColor);
}
Currently i cant see anything whenever i try to bind to the background. Maybe im missing something obvious, maybe i have to use something totally else. Any help would be appriciated!
CodePudding user response:
You would use a SolidColorBrush as value of the Setter:
<Setter Property="Background">
<Setter.Value>
<SolidColorBrush Color="{Binding}"/>
</Setter.Value>
</Setter>
Besides that, the ControlTemplate must also use the Background property:
<ControlTemplate TargetType="ListViewItem">
<Grid Height="30" Width="30"
Background="{TemplateBinding Background}"/>
</ControlTemplate>
Also note that when you set the ListViewItem's Template like this, the ItemTemplate
is not used at all. The ControlTemplate should have a ContentPresenter
.
<ControlTemplate TargetType="ListViewItem">
<Grid Height="30" Width="30"
Background="{TemplateBinding Background}">
<ContentPresenter/>
</Grid>
</ControlTemplate>
CodePudding user response:
Your data items should derive from System.Windows.Media.Brush, and then bind your grid's Background property in your template like this:
<ControlTemplate TargetType="ListViewItem">
<Grid Height="30" Width="30" Background="{Binding}"></Grid>
</ControlTemplate>