2017-10-10 126 views
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指揮工作。究竟是什麼問題,我哪裏出錯了?

回答

4

ButtonCommand必須是你能夠綁定到它的屬性:

public ICommand ButtonCommand { get; private set; } 

你已經將它定義爲一個字段:

public ICommand ButtonCommand; 
+2

嗯,這是令人尷尬的。謝謝 – Elsbeth

相關問題