我有一个视图模型,其中包含一个集合Item Attributes
,每个集合又包含一个图像的路径。集合中可能有来自0 .. N
项目属性的任何地方。
在我看来,堆栈面板包含三个相同的图像控件。每个图像控件都绑定到一个项目属性图像的路径:
- 图像控件 1 绑定到第一个项目属性的图像路径(在 ItemAttributes[0].Image 中找到)
- 图像控件 2 绑定到第二个项目属性的图像路径(在 ItemAttributes 1 .Image 中找到)
- 图像控件 3 绑定到第 3 个项目属性的图像路径(在 ItemAttributes[2].Image 中找到)
如果有超过 3 个属性,它们将被忽略。为了处理具有 0 - 2 个属性的可能性(这意味着 1 个或多个图像控件将绑定为 null),这反过来又给出了这篇文章中所述的错误,我添加了一个数据触发器,如下所示:
<DataTrigger Binding="{Binding Attribute1}" Value="{x:Null}">
<Setter Property="Source" Value="{x:Null}"/>
</DataTrigger>
此外,为了防止索引越界问题,我将视图模型中的项目属性拆分为三个属性(我最初返回 String.Empty,但将其更改为 null 以使用数据触发器):
public string Attribute1
{
get { return _item.Attributes.Count > 0 ? _item.Attributes[0].Image : null; }
}
public string Attribute2
{
get { return _item.Attributes.Count > 1 ? _item.Attributes[1].Image : null; }
}
public string Attribute3
{
get { return _item.Attributes.Count > 2 ? _item.Attributes[2].Image : null; }
}
所以我的问题是我想让这个数据触发器适用于所有三个图像属性和相应的图像控件(以及其他一些属性,如宽度、高度、边距等)。所以我认为,把它放在一个样式中,并将它作为一个静态资源引用。当我拥有三个具有不同名称的不同属性(Attribute1、Attribute2、Attribute3)时,这将不起作用。所以现在我坚持这样做:
<Image>
<Image.Style>
<Style TargetType="Image">
<Setter Property="Source" Value="{Binding Attribute1}" />
<Setter Property="Width" Value="44" />
<Setter Property="Height" Value="45" />
<Setter Property="Margin" Value="5" />
<Style.Triggers>
<DataTrigger Binding="{Binding Attribute1}" Value="{x:Null}">
<Setter Property="Source" Value="{x:Null}" />
</DataTrigger>
</Style.Triggers>
</Style>
</Image.Style>
</Image>
这对其他两个图像控件重复,除了 Attribute1 被 Attribute2 和 Attribute3 替换。
那么我想知道是否有一种方法可以绑定到集合,例如
<DataTrigger Binding="{Binding Attributes}" Value="{x:Null}">
<Setter Property="Source" Value="{x:Null}"/>
</DataTrigger>
...然后在模板之外指定我对图像控件绑定感兴趣的索引(我想就像将参数传递给数据触发器)。
任何想法......如果这是不可能的,还有另一种方法吗?