WPF MVVM模式中的事件绑定与棱镜库不适用于子用户控件中的按钮。
我有一个基本视图PreparationMockView
,其中有一个内容控件,它是一个子视图LeftBarPrepMockView
。现在,当单击LeftBarPrepMockView
中的按钮时,不会触发SelectedTaskCommand
。
下面是父视图和子视图以及各自的视图模型。
命名空间PreparationMockUp.ViewModels {公共类LeftBarPrepMockViewModel : ViewModelBase {私有只读IEventAggregator _eventAggregator;私有任务;只读字符串路径=LeftBarPrepMockViewModel公共LeftBarPrepMockViewModel(IEventAggregator ea) { _eventAggregator = ea;_eventAggregator.GetEvent().Subscribe((message) => InsertedCylinder(),ThreadOption.UIThread,true,x => x.Equals(PubSubMessages.InsertedBuildCylinder));SelectedTaskCommand = new DelegateCommand(NavigateToSelectedTask);} public ICommand SelectedTaskCommand { get;set;}私有列表_taskList;公共列表TaskList { get {返回_taskList;} set { _taskList = value;OnPropertyChanged(新PropertyChangedEventArgs("TaskList"));}} NavigateToSelectedTask(){ } }
发布于 2021-06-23 18:13:04
您可以将SelectedTaskCommand
绑定到名为root
的元素,但它并不存在于代码中。
Command="{Binding SelectedTaskCommand, ElementName=root}"
假设您指的是名为ItemsControl
的taskDisplayList
。然后可以使用ElementName
创建绑定,但仍然需要引用该元素的DataContext
才能绑定到视图模型。否则,绑定将搜索控件本身上的属性,该属性不存在。
Command="{Binding DataContext.SelectedTaskCommand, ElementName=taskDisplayList}"
另一种方法是使用RelativeSource
绑定LeftBarPrepMockView
用户控件。
Command="{Binding DataContext.SelectedTaskCommand, RelativeSource={RelativeSource AncestorType={x:Type local:LeftBarPrepMockView}}}"
当然,您也可以使用绑定到ItemsControl
或其他控件,而不使用ElementName
。
https://stackoverflow.com/questions/68104783
复制相似问题