【发布时间】:2017-10-10 13:13:11
【问题描述】:
我想将 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();
}
}
这就是我的应用导航的工作方式。我唯一的问题是我不能
在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 命令正常工作。究竟是什么问题,我哪里出错了?
【问题讨论】:
标签: c# wpf mvvm user-controls