I have an style in my Window.Resources
that i want to use in my behind code:
XAML :
<Window.Resources>
<Style x:Key="ListBoxItemStyle1" TargetType="ListBoxItem">
<Setter Property="BorderBrush" Value="Red"/>
<Setter Property="BorderThickness" Value="1"/>
</Style>
</Window.Resources>
C# :
ListBoxItem lbi = new ListBoxItem();
lbi.Style = (Style)Application.Current.Resources["ListBoxItemStyle1"];
.
.
.
MyListBox.Items.Add(lbi);
But this is not working, any solution?
If you use the FindResource
or TryFindResource
method, the Style
will be found regardless of whether you define it in the window or globally:
lbi.Style = TryFindResource("ListBoxItemStyle1") as Style;