最初我以为我可以使用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}" />