代码之家  ›  专栏  ›  技术社区  ›  Martin Liversage

Silverlight 3中ItemContainerStyle中的数据绑定问题

  •  3
  • Martin Liversage  · 技术社区  · 17 年前

    我无法在中使用数据绑定 ItemContainerStyle ListBox 银光3。它在WPF中运行良好。这是一个人为的例子来说明我的问题。我真正想做的是与 IsSelected

    我有一个 列表框 ObservableCollection<Item> 属于 Item 物体:

    public class Item {
      public String Name { get; }
      public Brush Color { get; }
    }
    

    以下是相关的Silverlight XAML:

    <ListBox x:Name="listBox" ItemsSource="{Binding .}">
      <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem">
          <Setter Property="Background" Value="{Binding Color}"/>
        </Style>
      </ListBox.ItemContainerStyle>
      <ListBox.ItemTemplate>
        <DataTemplate>
          <TextBlock Text="{Binding Name}"/>
        </DataTemplate>
      </ListBox.ItemTemplate>
    </ListBox>
    

    相同的XAML可以在WPF中使用,如果 TargetType="ListBoxItem" TargetType="{x:Type ListBoxItem}"

    WPF应用程序将在列表框中显示项目,并根据项目设置其背景颜色 Color 财产 项目 XamlParseException AG_E_RUNTIME_MANAGED_UNKNOWN_ERROR . 作为一个顽固的家伙,我甚至尝试删除失败的XAML,并创建了我自己的风格,而不是像这样:

      Binding binding = new Binding("Color");
      Setter setter = new Setter(ListBoxItem.BackgroundProperty, binding);
      Style style = new Style(typeof(ListBoxItem));
      style.Setters.Add(setter);
      listBox.ItemContainerStyle = style;
    

    如果我试着运行这个,我会得到一个 ArgumentException

    对项目的属性进行更改?

    2 回复  |  直到 17 年前
        1
  •  5
  •   Ben M    17 年前

    AFAIK Silverlight(甚至3)不支持样式设置器上的绑定。在加载每个项目时,您必须执行一些自定义逻辑来改变背景颜色——可能是通过在可视树中获取其父项(即容器)并将其设置在那里。

        2
  •  0
  •   Graeme Bradbury    17 年前

    您的Item类不够完整,无法识别,但颜色是画笔类型而不是颜色类型,对吗?因为您试图设置的背景属性需要笔刷。

    推荐文章