locked
How can I tell if a DataTemplate instance is selected in the containing ListView from XAML (data binding)?

    Question

  • I have a ListView that contains a collection of objects that are displayed in a list on one of my WinRT pages.  Currently I hide/show a slider bar on the DataTemplate for each list item by data binding the slider's Visibility property to an IsSelected property I created for the object.  The IsSelected property for each element in the collection is updated every time the ListView's item click event fires.  It works fine, but I spent a few hours trying to figure out a way to do this completely from XAML and did not succeed.

    Unfortunately WinRT does not support Multibinding or the the AncestoryType value for RelativeSource binding so there's no help there.  Is there a way to do this?  I'd like a pure XAML way to show/hide the slider in the DataTemplate based on whether or not the object it is bound to is currently the selected object in the ListView.  Preferably a XAML way that is not way too verbose if that's possible.


    -- roschler

    Monday, February 24, 2014 11:39 AM

Answers

  • You need C# to get this done, but at least this proposed solution has the C# in the viewmodel and nothing in the code-behind of the view itself. That's conform to the MVVM approach.
    Monday, February 24, 2014 6:40 PM

All replies

  • I would suggest to use a two-way binding between your ListView's SelectedItem and a property in your viewmodel (of the type that lives in the collection). That would make a click event handler obsolete.

    XAML would look like this:

    <ListView SelectionMode="Single" ItemsSource="{Binding YourCollection}" SelectedItem="{Binding YourSelectedItem, Mode=TwoWay}" />

    Monday, February 24, 2014 12:11 PM
  • I don't understand how that translates to something that triggers the Visibility data bindings for each slider child control to either Visible or Collapsed based on whether or not they are the selected item.

    -- roschler

    Monday, February 24, 2014 3:50 PM
  • Well: in the setter of 'YourSelectedItem' in the viewmodel, you set the IsSelected of the previous item to false, and for the new selected item you set it to true. Your current data bindings will update the visibility then.
    Monday, February 24, 2014 5:31 PM
  • Good idea.  So there's now way though to get rid of the IsSelected field hack?  I was hoping to do something in pure XAML.

    -- roschler

    Monday, February 24, 2014 6:22 PM
  • You need C# to get this done, but at least this proposed solution has the C# in the viewmodel and nothing in the code-behind of the view itself. That's conform to the MVVM approach.
    Monday, February 24, 2014 6:40 PM