Reputation: 1244
I already have this issue but I cannot remember how to solved it. (I think it's related to the visual tree or the datacontext of the a contextMenu in wpf)
I have a ParentViewModel with a Combobox and a ContentPresenter. The combobox display list of ChildViewModel. When one is selected it is displayed using the contentpresenter.
The ChildViewModel have a command to add items in a list. The command works find if it's binded on a button, but when it's done using a contextMenu the command is binded at the first execution but does not change if the ChildViewModel is changed (when another view model is selected in the combobox). The item is added to the previous selected ChildViewModel.
How can I solve this issue?
The Parent ViewModel:
public class Test1ViewModel:ObservableObject
{
public Test1ViewModel()
{
ViewModels = new ObservableCollection<TestViewModel>();
ViewModels.Add(new TestViewModel("View model1"));
ViewModels.Add(new TestViewModel("View model2"));
SelectedViewModel = ViewModels.FirstOrDefault();
}
private TestViewModel _selectedViewModel;
public TestViewModel SelectedViewModel
{
get { return _selectedViewModel; }
set
{
_selectedViewModel = value;
RaisePropertyChanged(() => SelectedViewModel);
}
}
public ObservableCollection<TestViewModel> ViewModels { get; set; }
}
The Parent View:
<StackPanel>
<ComboBox ItemsSource="{Binding ViewModels}" DisplayMemberPath="Name" SelectedItem="{Binding SelectedViewModel}"></ComboBox>
<ContentPresenter Content="{Binding SelectedViewModel}"/>
</StackPanel>
The Child ViewModel:
public class TestViewModel : ObservableObject
{
private int _idx;
public TestViewModel(string vmName)
{
Name = vmName;
ListOfValues = new ObservableCollection<string>();
ListOfValues.Add("Value" + _idx++);
ListOfValues.Add("Value" + _idx++);
AddItemCommand = new DelegateCommand(() => ListOfValues.Add("Value" + _idx++));
}
public string Name { get; private set; }
public ObservableCollection<string> ListOfValues { get; set; }
public DelegateCommand AddItemCommand { get; private set; }
}
The Child View
<StackPanel>
<Button Content="AddValue" Command="{Binding AddItemCommand}"/> <!--Binding work when selected view model is changed-->
<TextBlock Text="{Binding Name}"/>
<ListBox ItemsSource="{Binding ListOfValues}">
<ListBox.ContextMenu>
<ContextMenu>
<MenuItem Header="AddValue" Command="{Binding AddItemCommand}"/> <!--Binding doesn't work when selected view model is changed-->
</ContextMenu>
</ListBox.ContextMenu>
</ListBox>
Thanks in advance
Upvotes: 0
Views: 1747
Reputation: 1868
You are right.
The context menu is not in the visual tree, and only binds its datacontext once as the program is loaded.
In order to fix it, what I do is implement Josh Smith's Virtual Branch technique.
Look at this answer I posted to a similar question
Upvotes: 1