我已经有了这个问题,但我不记得如何解决它。 (我认为它与视觉树或wpf中contextMenu的datacontext有关)
我有一个带有Combobox和ContentPresenter的ParentViewModel。 ChildViewModel的组合框显示列表。选择一个时,将使用contentpresenter显示它。
ChildViewModel具有在列表中添加项目的命令。该命令可以查找是否在按钮上绑定,但是当使用contextMenu完成时,该命令在第一次执行时被绑定,但如果更改了ChildViewModel(在组合框中选择了另一个视图模型时)则不会更改。该项目将添加到之前选定的ChildViewModel。
我该如何解决这个问题?
父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; }
}
父视图:
<StackPanel>
<ComboBox ItemsSource="{Binding ViewModels}" DisplayMemberPath="Name" SelectedItem="{Binding SelectedViewModel}"></ComboBox>
<ContentPresenter Content="{Binding SelectedViewModel}"/>
</StackPanel>
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; }
}
儿童视图
<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>
提前致谢
答案 0 :(得分:1)