将命令绑定到 UserControl 中的 ViewModel
Binding Command to ViewModel inside UserControl
我想将 UserControl
绑定到 ViewModel 以使用 Commands/Events。
我的应用程序由一个 MainWindow
和一个 ContentControl
组成,用于显示 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
本身中使用命令(例如 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;
我想将 UserControl
绑定到 ViewModel 以使用 Commands/Events。
我的应用程序由一个 MainWindow
和一个 ContentControl
组成,用于显示 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
本身中使用命令(例如 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;