【问题标题】:Binding Command to ViewModel inside UserControl将命令绑定到 UserControl 中的 ViewModel
【发布时间】: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


    【解决方案1】:

    ButtonCommand 必须是您能够绑定到它的属性:

    public ICommand ButtonCommand { get; private set; }
    

    您已将其定义为字段:

    public ICommand ButtonCommand;
    

    【讨论】:

    • 嗯,这很尴尬。谢谢
    猜你喜欢
    • 2016-11-17
    • 2018-10-29
    • 1970-01-01
    • 1970-01-01
    • 2016-07-11
    • 1970-01-01
    • 1970-01-01
    • 2012-02-23
    • 2011-07-19
    相关资源
    最近更新 更多