Search code examples
c#wpflistboxstyleslistboxitem

Use Style From XAML In C#


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?


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;