views:

680

answers:

3

Hi,

I have a WPF app with many list based controls in a window, which all are bound to different CollectionViews.

At the window level is there a way to get the current selected item for the currently in focus list based control? I know I can do this with some fairly trivial code by looking for the in focus element but does WPF support this as a concept out of the box?

Something like Window.CurrentSelectedDataItem would be great. I am looking into using this as a way to centralize command management for enabling disabling commands based on a current selected data item.

Thanks, Jon

+1  A: 

I don't think that there is a property like you specify, but as an alternative you could register a ClassHandler for the ListBox.SelectionChanged event in your Window class:

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

This will get called whenever the selection changes in any ListBox in your application. You can use the sender argument to determine which ListBox it was that changed its selection, and cache this value for when you need it.

Andy
A: 

Have you looked at the target when the CanExecute event is raised? This is how our group wires up commands to act differently for different items.

When the CommandTarget is not set, the target for the command is the element which has keyboard focus. If the element which has keyboard focus does not support the command or cannot currently execute the command then the MenuItem would be grayed out.

sixlettervariables
A: 

I haven't tried this, but you could try using a MultiBinding with a converter to get to the correct item:

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

nullIfFalse returns the second parameter, if the first is true, null otherwise. coalesce returns the first non-null element.

David Schmitt