繁体   English   中英

从未知的ListBoxes ItemsSource中删除

[英]Deleting from unknown ListBoxes ItemsSource

我有一个包含多个ListBox的窗口,每个ListBox使用相同的KeyDown事件来确定是否按下了删除以突出显示条目。 我需要获取的是对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”事件处理程序中的绑定的引用。

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

// {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属性并将其DataContext为您的绑定类。

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM