[英]Menuitem command binding to ViewModel in UserControl located in Window
[英]Binding Command to ViewModel inside UserControl
我想将UserControl
绑定到ViewModel以使用命令/事件。 我的应用程序由一个内部带有ContentControl
的MainWindow
组成,该MainWindow
用于显示UserControls
(实际内容)以进行导航。
MainWindow.xaml
<Window>
<Window.Resources>
<DataTemplate DataType="">
<View: />
</DataTemplate>
</Window.Resources>
<Menu>
<MenuItem Header="Connection" Command="..." />
</Menu>
<Grid>
<ContentControl Content="{Binding SelectedViewModel}" />
</Grid>
</Window>
MainViewModel.cs
class MainViewModel : ViewModelBase {
public ICommand MenuCommand;
private object _SelectedViewModel;
public object SelectedViewModel
{
get { return _SelectedViewModel; }
set
{
_SelectedViewModel = value;
RaisePropertyChanged("SelectedViewModel");
}
}
public MainViewModel()
{
ICommand = new RelayCommand(MenuClick);
}
private void MenuClick(object obj)
{
SelectedViewModel = new ConnectionViewModel();
}
}
这就是我的应用程序导航的工作方式。 我唯一的问题是,我似乎无法在UserControl
本身中使用Commands(例如Button
)。
ConnectionView.xaml
<UserControl>
<Grid>
<Button Command="{Binding ButtonCommand}" Content="Button" />
</Grid>
</UserControl>
ConnectionViewModel.cs
class ConnectionViewModel : ViewModelBase {
public ICommand ButtonCommand;
public ConnectionViewModel()
{
ButtonCommand = new RelayCommand(ButtonClick);
}
private void ButtonClick(object obj)
{
MessageBox.Show("Clicked");
}
}
我可以在UserControl
视图中填充ListViews
,但不能使Button
命令正常工作。 到底是什么问题,我哪里出问题了?
ButtonCommand
必须是一个属性,您才能绑定到它:
public ICommand ButtonCommand { get; private set; }
您已将其定义为字段:
public ICommand ButtonCommand;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.