Change ListBox item style at run-time
I have a listbox where the items are styled using a ResourceDictionary style which is then attached to the ItemContainerStyle property. This gives my ListBoxItems a BorderThickness of let's say 1.
Now I want to collapse the items individually, so I use Visibility.Collapsed but for some reason the border that the ItemContainerStyle has created does not vanish with the rest of the list box item. It is as if it has created a layer behind my item and this remain开发者_JAVA百科s despite the item being collapsed.
How do I set the ListBoxItem's (or this extra layer's) BorderThickness to 0 at run-time?
Regards sk
try using a custom triggers:
<Style TargetType="{x:Type ListBoxItem}">
<Style.Triggers>
<Trigger Property="Visibility" Value="Collapsed">
<Setter Property="BorderThickness" Value="0,0,0,0"/>
</Trigger>
<Trigger Property="Visibility" Value="Visible">
<Setter Property="BorderThickness" Value="0,0,0,1"/>
</Trigger>
</Style.Triggers>
</Style>
Obviously change your border thickness values, but this should do the trick (or something very close to this)
I tried to reproduce the issue, but found that the border does collapse as expected:
<StackPanel>
<StackPanel.Resources>
<BooleanToVisibilityConverter x:Key="BooleanToVisibility" />
<Style x:Key="ListBoxItemStyle" TargetType="ListBoxItem">
<Setter Property="BorderBrush" Value="Black" />
<Setter Property="BorderThickness" Value="1" />
</Style>
</StackPanel.Resources>
<CheckBox x:Name="_show"
Content="Show Item 2"
IsChecked="True" />
<ListBox ItemContainerStyle="{StaticResource ListBoxItemStyle}">
<ListBoxItem Content="Item 1" />
<ListBoxItem Content="Item 2">
<ListBoxItem.Visibility>
<Binding ElementName="_show"
Path="IsChecked"
Converter="{StaticResource BooleanToVisibility}" />
</ListBoxItem.Visibility>
</ListBoxItem>
<ListBoxItem Content="Item 3" />
</ListBox>
</StackPanel>
Are you certain the ListBoxItem is the object being collapsed (as opposed to the UI object in the ListBoxItem)?
foreach(ListBoxItem item in listBox1.Items){
item.BorderThickness = new Thickness(0);
}
This is the answer but I wouldnt recommend because you cant undo the style to bring back what was original instead you should choose some different approach with databinding on the basis of certain states.
精彩评论