MVVM Listbox DataTemplate SelectedItem
Posted
by
StinkerPeter
on Stack Overflow
See other posts from Stack Overflow
or by StinkerPeter
Published on 2011-11-25T01:43:43Z
Indexed on
2011/11/25
1:51 UTC
Read the original article
Hit count: 291
I am using a ListBox with a DataTemplate
as shown below (xaml simplified and variable names changed).
<ListBox ItemsSource="{Binding Path=ObservCollectionItems}"
SelectedItem="{Binding Path=SelectedItemVar, Mode=TwoWay}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding SomeVar}" />
<Border>
<StackPanel>
<Button Content="String1"
Command="{Binding DataContext.Command1}
RelativeSource={RelativeSource FindAncestor, ListBox, 1}}" />
<Button Content="String2"
Command="{Binding DataContext.Command2}
RelativeSource={RelativeSource FindAncestor, ListBox, 1}}" />
</StackPanel>
</Border>
</StackPanel>
</DataTemplate>
<ListBox.ItemTemplate>
</ListBox>
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 TextBlock
or the Border
, but not when I click either button. I found a non-MVVM solution to this problem here. I do not want to add code in the file-behind to solve this, as they did in the link.
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.
Finally, I found this Command="{Binding DataContext.CommandName} RelativeSource={RelativeSource FindAncestor, ListBox, 1}
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 CommandName
.
© Stack Overflow or respective owner