I want do something like this.
<Style TargetType="{x:Type ListBoxItem}" >
<Setter Property="Style">
<Setter.Value>
<Border Style="{StaticResource BorderStyle}" Width="200" >
</Border>
</Setter.Value>
</Setter>
</Style>
<Style x:Key="BorderStyle" TargetType="{x:Type Border}">
<Setter Property="Background" Value="{StaticResource BackBrush}" />
<Setter Property="BorderBrush" Value="Black" />
<Setter Property="BorderThickness" Value="0.5" />
<Setter Property="CornerRadius" Value="4" />
<Setter Property="Margin" Value="4" />
<Setter Property="Padding" Value="4" />
</Style>
But it gives next error
Cannot add content of type ‘System.Windows.Controls.Border’ to an object of type ‘System.Object’.
and the code which use it
for (int i = 0; i < 10; i++)
{
ListBoxItem lbItem = new ListBoxItem();
lbItem.Content = "Item" + i;
lb1.Add(lbItem);
}
where “lb1” is my ListBox in xaml form
How can i give ListBoxItemStyle properly?
It looks like you’re confused about the semantics of XAML. Until you get more used to XAML it might help to think about it as the C# equivalent. This is essentially what you’re doing right now:
One issue is that you’re setting a Style for the ListBoxItem from a Setter inside the Style for your ListBoxItem, which is of course going to cause some sort of problem with recursion. So removing that extra Style from the code we get:
This is invalid because it’s trying to set a Style property (of Type Style) to a Border object. This is essentially what’s at the core of the error you’re seeing.
What you really want in this case is to change the ListBoxItem ControlTemplate to incorporate your Border Style. This is the default Style modified to use your Border instead of the standard one using TemplateBindings to set its properties: