从未知的ListBoxes ItemsSource中删除

时间:2019-02-08 16:33:59

标签: c# wpf binding

我有一个包含多个ListBox的窗口,每个ListBox使用相同的KeyDown事件来确定是否为突出显示的条目按下了Delete键。我需要获取的是对ListBox选定绑定源的引用,因此我可以从中删除选定值,我可以看到带有以下内容的对象:

var sourceObject = box.ItemsSource;

这只是返回绑定到ListBox的项目的IEnumerable列表。

如何获取绑定的源属性(引用),以便删除基础值?

这是xaml:

<ListBox x:Name="listTest1" ItemsSource="{Binding AllTest1Values}" HorizontalAlignment="Left" Height="60" Margin="341,390,0,0" VerticalAlignment="Top" Width="156" KeyDown="ListBox_KeyDown">

<ListBox x:Name="listTest2" ItemsSource="{Binding AllTest2Values}" HorizontalAlignment="Left" Height="60" Margin="341,390,0,0" VerticalAlignment="Top" Width="156" KeyDown="ListBox_KeyDown">

<ListBox x:Name="listTest3" ItemsSource="{Binding AllTest3Values}" HorizontalAlignment="Left" Height="60" Margin="341,390,0,0" VerticalAlignment="Top" Width="156" KeyDown="ListBox_KeyDown">

如您所见,事件始终是相同的,但是绑定是不同的。这就是为什么我需要找到一种方法来获取对“ ListBox_KeyDown”事件处理程序中的绑定的引用。

2 个答案:

答案 0 :(得分:0)

通常,您需要数据上下文。

// {Event} needs to be replaced with your event name, such as Click
// {BindingClass} need to be replaced with the name of your binding class, such as ListBoxItems

private void ListBox_{Event}(object sender, RoutedEventArgs e)
{
    var listbox = (FrameworkElement)sender;
    var dataContext = ({BindingClass})listbox.DataContext;
}

以上,您的事件处理程序将提供发送方,并且如果该发送方是FrameworkElement,则您应该能够对其进行强制转换并获得一个列表框对象。从那里,您可以检查DataContext属性并将其强制转换为您的绑定类。

另一种设计是将ListBox组件子类化,并添加自己的属性以对您最有用的方式表示绑定源。这样,您就可以在通用事件处理程序中访问该属性,而不必担心尝试使用反射或其他方法来确定绑定源对象是什么。

答案 1 :(得分:0)

如何获取绑定的源属性(引用),以便删除基础值?

box.ItemsSource确实为您提供了对源集合的引用。但是由于ItemsSource属性的类型为IEnumerable,因此您需要先将值强制转换为支持删除项目的对象,然后才能删除任何项目。 ICollection<T>接口应该可以使用。例如,它是由List<T>ObservableCollection<T>实施的。

var x = box.ItemsSource as ICollection<string>;
if (x != null)
    x.Remove("...");