ListBoxItem模板

时间:2015-05-27 10:35:30

标签: c# wpf data-binding

我的问题使用以下代码,绑定IsAvailable类的MyListBoxItem属性。我目前的解决方案:

<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的值经历了“两个绑定”。第一个将值绑定到Tag的{​​{1}}属性,然后在样式触发器中,触发器检查其值并设置Label的属性。当我使用Label时它不起作用,因为Binding="{Binding IsAvailable, RelativeSource={RelativeSource AncestorType={x:Type local:MyListBoxItem}}}"无法看到Style的任何祖先(或类似的原因),导致绑定错误(使用代码4或40个或许),对于添加到Label的每个项目。

最后:我可以使解决方案更简单,或者没有其他(更好)解决方案吗?

我忘了提到一件重要的事情,抱歉:我将ListBox放在ListBox的资源中,因为我有更多模板(它们基本上不同,所以我不能用触发器来设置它们,我必须在它之间切换......

1 个答案:

答案 0 :(得分:0)

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属性设置为BindingMyListBoxItem集合。

相关问题