[英]Change ListBox item style at run-time
我有一個列表框,其中使用ResourceDictionary樣式對項目進行樣式設置,然后將其附加到ItemContainerStyle屬性。 這使我的ListBoxItems的BorderThickness為1。
現在,我想單獨折疊這些項目,因此我使用Visibility.Collapsed,但由於某種原因,ItemContainerStyle創建的邊框不會與列表框項目的其余部分一起消失。 好像它已經在我的物品后面創建了一個圖層,並且即使該物品被折疊了,該圖層仍然保留。
如何在運行時將ListBoxItem(或此附加層的)BorderThickness設置為0?
問候sk
嘗試使用自定義觸發器:
<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>
顯然更改邊框的粗細值,但這可以解決問題(或非常接近此目的的方法)
我試圖重現此問題,但發現邊框確實按預期崩潰了:
<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>
您確定ListBoxItem是折疊的對象(與ListBoxItem中的UI對象相對)嗎?
foreach(ListBoxItem item in listBox1.Items){
item.BorderThickness = new Thickness(0);
}
這是答案,但我不建議這樣做,因為您不能撤消該樣式以恢復原始樣式,而應基於某些狀態選擇一些不同的數據綁定方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.