替换 ItemContainerTemplate 的一部分

拉尔夫

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

对于我的应用程序中的所有 ListViews,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>

我怎么能将此 ItemContainerTemplate 用于所有 ListView,但为每个 ListView 更改“StaticResource Article”?

一点

您可以将 绑定Image.Source到 的Tag 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和 aProperty来设置默认Image源。

自定义ListView可能看起来像这样并放置在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
}

此外,样式必须绑定到 DefaultImageSource Property

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

现在它可以像这样使用

xmlns:cc="clr-namespace:Your.Namespace"
.
.
<cc:ListViewWithDefaultImage ItemsSource="{Binding Samples}" ItemTemplate="{DynamicResource MyContainerTemplate}" DefaultImageSource="{StaticResource Article}"/>

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章