[英]Binding Command to ViewModel inside UserControl
I want to bind a UserControl
to a ViewModel to use Commands/Events. 我想将
UserControl
绑定到ViewModel以使用命令/事件。 My application consists of a MainWindow
with a ContentControl
inside, which is used to display a UserControls
(the actual content) for navigation purposes. 我的应用程序由一个内部带有
ContentControl
的MainWindow
组成,该MainWindow
用于显示UserControls
(实际内容)以进行导航。
MainWindow.xaml 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 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();
}
}
This is how the navigation of my app works. 这就是我的应用程序导航的工作方式。 The only problem I'm having is that I can't seem to use Commands (
Button
for example) in the UserControl
itself. 我唯一的问题是,我似乎无法在
UserControl
本身中使用Commands(例如Button
)。
ConnectionView.xaml ConnectionView.xaml
<UserControl>
<Grid>
<Button Command="{Binding ButtonCommand}" Content="Button" />
</Grid>
</UserControl>
ConnectionViewModel.cs ConnectionViewModel.cs
class ConnectionViewModel : ViewModelBase {
public ICommand ButtonCommand;
public ConnectionViewModel()
{
ButtonCommand = new RelayCommand(ButtonClick);
}
private void ButtonClick(object obj)
{
MessageBox.Show("Clicked");
}
}
I can fill ListViews
in the UserControl
View but I can't get the Button
Command working. 我可以在
UserControl
视图中填充ListViews
,但不能使Button
命令正常工作。 What exactly is the problem, where did I go wrong? 到底是什么问题,我哪里出问题了?
ButtonCommand
must be a property for you to be able to bind to it: ButtonCommand
必须是一个属性,您才能绑定到它:
public ICommand ButtonCommand { get; private set; }
You have defined it as a field: 您已将其定义为字段:
public ICommand ButtonCommand;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.