[英]Relative binding in style of control inside ListBoxItem template
我的問題是以下代碼與MyListBoxItem
類的IsAvailable
屬性綁定IsAvailable
。 我當前的解決方案:
<ListBox ItemTemplate="{StaticResource myTemplate}">
<ListBox.Resources>
<DataTemplate x:Key="myTemplate" DataType="{x:Type local:MyListBoxItem}">
<Label Foreground="Green" Content="{Binding Title}" Tag="{Binding IsAvailable}">
<Label.Style>
<Style TargetType="{x:Type Label}">
<Style.Triggers>
<DataTrigger Binding="{Binding Tag, RelativeSource={RelativeSource Self}}" Value="True">
<Setter Property="FontWeight" Value="Bold"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Label.Style>
</Label>
</DataTemplate>
... (more datatemplates)
</ListBox.Resources>
</ListBox>
我的問題:在我的解決方案中, IsAvailable
的值“通過”兩個綁定。 第一個將值綁定到Label
的Tag
屬性,然后在樣式觸發器中,觸發器檢查其值並設置Label
的屬性。 當我使用Binding="{Binding IsAvailable, RelativeSource={RelativeSource AncestorType={x:Type local:MyListBoxItem}}}"
它無效,因為Style
無法看到Label
任何祖先(或類似原因) ),則對於添加到ListBox
每個項目都會導致綁定錯誤(可能是代碼4或40)。
所以最后:我可以使解決方案更簡單,還是沒有其他(更好的)解決方案?
抱歉 ,我忘了提到一個重要的事情:我將DataTemplate
放在ListBox的資源中,因為我有更多的模板(它們基本上是不同的,所以我不能用觸發器設置樣式),有時不得不在它們之間進行切換。 ..
ItemTemplate
將采用ItemsSource
綁定到的類型。 因此,您應該能夠簡單地綁定到IsAvailable
,因為ListBox的項目類型是MyListBoxItem
。 嘗試這個:
<ListBox ItemsSource="...">
<ListBox.ItemTemplate>
<DataTemplate>
<Label Foreground="Green" Content="{Binding Title}" Tag="{Binding IsAvailable}">
<Label.Style>
<Style TargetType="{x:Type Label}">
<Style.Triggers>
<DataTrigger Binding="{Binding Tag, RelativeSource={RelativeSource Self}}" Value="True">
<Setter Property="FontWeight" Value="Bold"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Label.Style>
</Label>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
您需要將ItemsSource
屬性設置為Binding
到MyListBoxItem
集合。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.