任何更好的方法都可以将数字添加到ListView的ItemContainerStyle中
本文关键字:ListView ItemContainerStyle 添加 更好 方法 都可以 任何 数字 | 更新日期: 2023-09-27 18:34:48
我正在尝试稍微扩展我的ListView的ItemContainerStyle,并添加一个绑定到属性的TextBlock。它应该显示ListView.SelectedItems.Count。
目前我有一个可行的解决方案,但我对它不满意(我怀疑有更简单的方法,可能更干净(。它是这样的:
<Style x:Key="MyItemStyle" TargetType="ListViewItem">
<!--Some code-->
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListViewItem">
<!--Some code-->
<TextBlock DataContext="{Binding ElementName=contentPresenter, Path=DataContext}" Text="{Binding Number}" Foreground="Red"/>
这个想法非常简单 - 我将 DataContext 设置为与 contentPresenter
相同,这意味着如果我在我的 ItemClass 中有一个属性编号并且我放在那里Item.Number = myList.SelectedItems.Count;
一切正常。
但是有没有其他方法可以以这种方式做到这一点?我的 ItemClass 中没有其他属性?以某种方式扩展列表视图或列表视图项?
最初我以为我可以使用ElementName
绑定来检索ListView
,然后将TextBlock
的Text
绑定到ListView
的SelectedItems.Count
。像下面这样——
<!-- this won't work -->
<TextBlock Text="{Binding Path=SelectedItems, ElementName=myList, Converter="{StaticResource GetCountConverter}"}" />
但是,与 SelectedItem
依赖项属性不同,这不起作用SelectedItems
因为它只是一个普通的只读属性。
常见的解决方法是创建具有几个附加属性的静态帮助程序类。像这样的东西——
public static class ListViewEx
{
public static int GetSelectedItemsCount(DependencyObject obj)
{
return (int)obj.GetValue(SelectedItemsCountProperty);
}
public static void SetSelectedItemsCount(DependencyObject obj, int value)
{
obj.SetValue(SelectedItemsCountProperty, value);
}
public static readonly DependencyProperty SelectedItemsCountProperty =
DependencyProperty.RegisterAttached("SelectedItemsCount", typeof(int), typeof(ListViewEx), new PropertyMetadata(0));
public static bool GetAttachListView(DependencyObject obj)
{
return (bool)obj.GetValue(AttachListViewProperty);
}
public static void SetAttachListView(DependencyObject obj, bool value)
{
obj.SetValue(AttachListViewProperty, value);
}
public static readonly DependencyProperty AttachListViewProperty =
DependencyProperty.RegisterAttached("AttachListView", typeof(bool), typeof(ListViewEx), new PropertyMetadata(false, Callback));
private static void Callback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if ((bool)e.NewValue)
{
var listView = d as ListView;
if (listView == null) return;
listView.SelectionChanged += (s, args) =>
{
SetSelectedItemsCount(listView, listView.SelectedItems.Count);
};
}
}
基本上在这里,我创建了一个SelectedItemsCount
附加属性来利用数据绑定。每当触发SelectionChanged
时,代码都会将附加属性更新为SelectedItems
的Count
,以便它们始终同步。
然后在 xaml 中,您需要首先将帮助程序附加到ListView
(以便检索ListView
实例并订阅其SelectionChanged
事件(,
<ListView x:Name="myList" local:ListViewEx.AttachListView="true"
最后,更新 TextBlock
XAML 中的绑定。
<TextBlock Text="{Binding Path=(local:ListViewEx.SelectedItemsCount), ElementName=myList}" />