替换ItemContainerTemplate的一部分

时间:2018-09-19 15:20:25

标签: wpf xaml staticresource

在WPF应用程序中,我有几个ListView,它们的外观与ItemContainerTemplate相似:列表中的每个项目都会有一个小图像和一个文本(名称)。 所述图像取决于与基础对象的绑定:如果在相应的属性中设置了图像,则显示该对象的图像。如果基础对象未设置图像,则显示默认图像。 取决于ListView的默认图像是不同的:对于商品列表,显示默认商品图像,但是对于客户列表,显示默认商品图像。

对于我的应用程序中的所有ListView,ItemContainerTemplate除了默认图像外基本相同。如果我可以对所有ListView使用一个通用的ItemContainerTemplate,那就太好了,但是如何替换每个ListView的默认图像。

我当前的ItemContainerTemplate基本上是这样的:

<ItemContainerTemplate x:Key="MyContainerTemplate">
.
.
.
<Image>
 <Image.Style>
  <Style>
   <Setter Property="Image.Source" Value="{Binding Image}" />
   <Style.Triggers>
    <DataTrigger Binding="{Binding Image}" Value="{x:Null}">
     <Setter Property="Image.Source" Value="{StaticResource Article}" />
    </DataTrigger>
   </Style.Triggers>
  </Style>
 </Image.Style>
</Image>
.
.
.
</ItemContainerTemplate>

我如何在所有ListView上使用此ItemContainerTemplate,但如何为每个ListContainerTemplate更改“ StaticResource Article”?

1 个答案:

答案 0 :(得分:1)

您可以将Image.Source的{​​{1}}绑定到Tag的{​​{1}}(或Attached Property)上,以分别进行设置。

要绑定到Property中的ListView Tag,请将“源”更改为此

Property

现在ItemContainerTemplate可以从“外部”设置

<Setter Property="Image.Source" Value="{Binding Path=Tag, RelativeSource={RelativeSource AncestorType={x:Type ListView}}}"/>

修改

一种更简单的方法是将自定义Image.Source<ListView ItemTemplate="{DynamicResource MyContainerTemplate}" Tag="{StaticResource Article}"/> 一起使用,仅用于设置默认Listview的来源。

自定义Property可能看起来像这样,并放置在Image中。

ListView

此外,样式必须绑定到DefaultImageSource Your.Namespace

public class ListViewWithDefaultImage : ListView
{
    public ListViewWithDefaultImage() : base() { }
    public string DefaultImageSource
    {
        get { return (string)this.GetValue(DefaultImageSourceProperty); }
        set { this.SetValue(DefaultImageSourceProperty, value); }
    }

    public static readonly DependencyProperty DefaultImageSourceProperty = DependencyProperty.Register("DefaultImageSource", typeof(string), typeof(ListViewWithDefaultImage), new PropertyMetadata(String.Empty));
    //Note: its possible to replace String.Empty with a default Path for Default Images
}

现在可以像这样使用

Property