2
我想將UserControl
綁定到ViewModel以使用命令/事件。 我的應用程序由一個MainWindow
和一個ContentControl
組成,用於顯示用於導航的UserControls
(實際內容)。將用戶控件中的ViewModel綁定命令
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
指揮工作。究竟是什麼問題,我哪裏出錯了?
嗯,這是令人尷尬的。謝謝 – Elsbeth