title: How to programmatically deselect a ListViewItem in c++/cx?
body: <p>I have a <code>ListView</code> with <code>SelectionMode</code> set to <code>Single</code> in XAML and want to deselect the selected item programmatically in the code-behind, which I tried to accomplish by this line in the <code>MenuFlyout-&gt;Closed</code> event Handler (every <code>ListViewItem</code> has a <code>MenuFlyout</code> attached to it):</p>
  
  <pre><code>NotationListView-&gt;SelectedIndex = -1;
  </code></pre>
  
  <p>Unfortunately, this does not work and the app crashes. Any other value works and selects the corresponding <code>ListViewItem</code>, but <code>-1</code> just doesn't do what I expected.</p>
  
  <p>How can I do this?</p>
  
  <h2>EDIT: my current workaround</h2>
  
  <h3>XAML definition of <code>ListView</code> (shortened):</h3>
  
  <pre><code>&lt;ListView x:Name="NotationListView" 
      SelectionMode="None" 
      IsItemClickEnabled="True" 
      ItemClick="NotationListView_ItemClicked"/&gt;
  </code></pre>
  
  <h3>C++/CX definition of NotationListView_ItemClicked() (shortened):</h3>
  
  <pre><code>ListViewItem^ item = (ListViewItem^) ((TextBlock^) e-&gt;ClickedItem)-&gt;Parent;
  item-&gt;Foreground = ref new SolidColorBrush(Colors::Green);
  Flyout::ShowAttachedFlyout(item);
  selectedItem = item;
  </code></pre>
  
  <p><code>selectedItem</code> is just a variable declared in the xaml.h file that stores the selected Item. That way, I can use it easily in Click-EventHandlers of the <code>MenuFlyoutItems</code>.
  Now you may notice that I don't have any way of accessing the index of the clicked Item, which I desperately need. But because all the <code>ListViewItems</code> are created programmatically, I can just add this to the end of the creation:</p>
  
  <pre><code>auto items = NotationListView-&gt;Items;
  Box&lt;unsigned int&gt;^ indexBox = ref new Box&lt;unsigned int&gt;(items-&gt;Size);
  item-&gt;Tag = indexBox;
  items-&gt;Append(item);
  </code></pre>
  
  <p>Now I get the Index of every item simply with the line</p>
  
  <pre><code>unsigned int i = ((Box&lt;unsigned int&gt;^)selectedItem-&gt;Tag)-&gt;Value;
  </code></pre>
  
  <h3>C++/CX definition of NotationFlyout_Closed():</h3>
  
  <p>this is as easy as it gets.</p>
  
  <pre><code>if (selectedItem){
      selectedItem-&gt;Foreground = ref new SolidColorBrush(Colors::Black);
      selectedItem = nullptr;
  }
  </code></pre>