Note that there are some explanatory texts on larger screens.

plurals
  1. POMVVM Listbox DataTemplate SelectedItem
    primarykey
    data
    text
    <p>I am using a ListBox with a <code>DataTemplate</code> as shown below (xaml simplified and variable names changed).</p> <pre><code>&lt;ListBox ItemsSource="{Binding Path=ObservCollectionItems}" SelectedItem="{Binding Path=SelectedItemVar, Mode=TwoWay}"&gt; &lt;ListBox.ItemTemplate&gt; &lt;DataTemplate&gt; &lt;StackPanel&gt; &lt;TextBlock Text="{Binding SomeVar}" /&gt; &lt;Border&gt; &lt;StackPanel&gt; &lt;Button Content="String1" Command="{Binding DataContext.Command1} RelativeSource={RelativeSource FindAncestor, ListBox, 1}}" /&gt; &lt;Button Content="String2" Command="{Binding DataContext.Command2} RelativeSource={RelativeSource FindAncestor, ListBox, 1}}" /&gt; &lt;/StackPanel&gt; &lt;/Border&gt; &lt;/StackPanel&gt; &lt;/DataTemplate&gt; &lt;ListBox.ItemTemplate&gt; &lt;/ListBox&gt; </code></pre> <p>I need the SelectedItemVar (dependency property) to update when I click on one of the buttons. SelectedItemVar is then used for the respective button's command. SelectedItemVar does update when I click on the <code>TextBlock</code> or the <code>Border</code>, but not when I click either button. I found a non-MVVM solution to this problem <a href="https://stackoverflow.com/questions/765984/wpf-listboxitems-with-datatemplates-how-do-i-reference-the-clr-object-bound-to">here</a>. I do not want to add code in the file-behind to solve this, as they did in the link.</p> <p>Is there a clean solution that can be done in XAML. Beyond the non-MVVM solutions, I have not found anyone with this problem. I would have thought this was fairly common.</p> <p>Finally, I found this <code>Command="{Binding DataContext.CommandName} RelativeSource={RelativeSource FindAncestor, ListBox, 1}</code> for the Command binding. I do not fully understand what it is doing, but I do know that the command wasn't firing when I was binding directly to <code>CommandName</code>.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload