Nemanja Vidačković
Nemanja Vidačković

Reputation: 73

How to set the Style property of a ListBox control in code

I have a part of Xaml code that I want to write in C# code. Code:

<ListBox Name="listBox">
    <ListBox.ItemContainerStyle>
        <Style TargetType="{x:Type ListBoxItem}">
            <Setter Property="Focusable" Value="False"/>
        </Style>
    </ListBox.ItemContainerStyle>
</ListBox>

I tried:

listBox.ItemContainerStyle = new Style();

Setter setter = new Setter();
setter.Property = ....??
setter.Value = true;

listBox.ItemContainerStyle.Setters.Add(setter);

But cant find the Focusable property to insert in setter. Can anyone help?

Upvotes: 1

Views: 441

Answers (2)

gandalf
gandalf

Reputation: 470

setter.Property = ListBoxItem.FocusVisualStyleProperty;

This link can help you. It talks about creating templates in code behind.

Upvotes: 2

bene_rawr
bene_rawr

Reputation: 119

This will work just fine.

Style style = new Style(typeof(ListBoxItem));
style.Setters.Add(new Setter(ListBoxItem.FocusableProperty, false));

listBox.ItemContainerStyle = style;

Upvotes: 1

Related Questions