如何为窗口确定WPF SelectedItem

时间:2020-03-06 14:21:56  来源:igfitidea点击:

我有一个WPF应用程序,在一个窗口中有很多基于列表的控件,所有控件都绑定到不同的CollectionViews。

在窗口级别,是否有办法为基于焦点列表的控件获得当前选定的项目?我知道我可以通过查找in focus元素来使用一些相当琐碎的代码来做到这一点,但是WPF是否将其作为开箱即用的概念来支持?

像Window.CurrentSelectedDataItem这样的东西会很棒。我正在研究使用它作为集中命令管理的方法,以便基于当前选定的数据项启用禁用命令。

谢谢,
乔恩

解决方案

我认为没有像我们指定的属性,但是作为替代,我们可以在Window类中为ListBox.SelectionChanged事件注册一个ClassHandler:

EventManager.RegisterClassHandler(typeof(ListBox), ListBox.SelectionChanged,
    new SelectionChangedEventHandler(this.OnListBoxSelectionChanged));

每当应用程序中任何列表框中的选择更改时,都会调用此方法。我们可以使用sender参数来确定是哪个ListBox更改了其选择,并在需要时缓存此值。

我没有尝试过,但是我们可以尝试将MultiBinding与转换器一起使用以获取正确的项目:

<MultiBinding Converter="{StaticResource coalesce}">
    <MultiBinding.Bindings>
        <MultiBinding Converter="{StaticResource nullIfFalse}">
            <MultiBinding.Bindings>
                 <Binding ElementName="List1" Path="HasFocus" />
                 <Binding ElementName="List1" Path="SelectedItem" />

nullIfFalse返回第二个参数,如果第一个为true,否则返回null。 coalesce返回第一个非null元素。