我想将UserControl
绑定到ViewModel以使用命令/事件。
我的应用程序由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();
}
}
这就是我的应用程序导航的工作方式。我遇到的唯一问题是我看起来不可能
在Button
本身中使用命令(例如UserControl
。
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");
}
}
我可以在ListViews
视图中填写UserControl
,但我无法让Button
命令正常工作。究竟是什么问题,我哪里出错了?
答案 0 :(得分:4)
ButtonCommand
必须是您能够绑定到它的属性:
public ICommand ButtonCommand { get; private set; }
您已将其定义为字段:
public ICommand ButtonCommand;