【问题标题】:Problems with data binding in ItemContainerStyle in Silverlight 3Silverlight 3 中 ItemContainerStyle 中的数据绑定问题
【发布时间】:2010-11-13 16:20:46
【问题描述】:

我无法在 Silverlight 3 中为 ListBox 使用 ItemContainerStyle 中的数据绑定。它在 WPF 中运行良好。这是一个人为的例子来证明我的问题。我真正想要的是绑定到IsSelected 属性,但我认为这个例子更容易理解。

我有一个 ListBox 绑定到 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>

如果将 TargetType="ListBoxItem" 替换为 TargetType="{x:Type ListBoxItem}",则可以在 WPF 中使用相同的 XAML。

WPF 应用程序将显示列表框中的项目并根据Item 对象的Color 属性设置它们的背景颜色。但是,Silverlight 应用程序失败,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;

如果我尝试运行它,我会在 Silverlight 控件初始化后收到 ArgumentException

我做错了什么?如何将ItemContainerStyle 上的属性绑定到项目的属性?

【问题讨论】:

  • 看起来是一样的,但它在一年多前被转发给 Silverlight 团队,但修复程序仍然没有进入 Silverlight 3。
  • liversage - 你有没有找到这样做的好方法?

标签: wpf silverlight data-binding listbox


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    您的 Item 类还不够完整,无法说明,但 Color 是 Brush 类型而不是 Color 类型,对吗?由于您尝试设置的背景属性需要画笔。

    【讨论】:

    • 对不起,我忘了给 Item 的属性添加类型。属性颜色的类型为画笔。我没有包含我所有的代码以避免写一堵文字墙。但是,我有一个工作示例,它在 WPF 中做正确的事情,但在 Silverlight 中失败。
    猜你喜欢
    • 2011-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多