【问题标题】:ICommand is not executed in WPF applicationICommand 未在 WPF 应用程序中执行
【发布时间】:2020-06-01 21:41:07
【问题描述】:

我有一个 WPF 应用程序,它带有一个绑定到 MessageCommand 的按钮。为了简单起见,该应用程序只有一个应该显示消息框的按钮。但是,当我单击按钮时,什么也没有发生。我遵循CodeProject 的指示,但我不知道我错过了什么,尽管关于这个主题有很多问题和答案。

XAML 文件:

<Window x:Class="CommandTestProject.MainWindow"
        ...
        xmlns:local="clr-namespace:CommandTestProject"
        xmlns:vw="clr-namespace:CommandTestProject.ViewModel"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Window.DataContext>
        <vw:ViewModelMsg/>
    </Window.DataContext>
    <Grid>
        <Button Content="Click"
                Command="{Binding Path=MessageCommand}"/>
    </Grid>
</Window>

ViewModel 类:

using CommandTestProject.Commands;
using System;
using System.Windows;
using System.Windows.Input;

namespace CommandTestProject.ViewModel
{
    public class ViewModelMsg
    {
        private ShowMessage showMsg;
        public ViewModelMsg()
        {
            showMsg = new ShowMessage(this);
        }

        internal ICommand MessageCommand
        {
            get
            {
                return showMsg;
            }
        }
        internal void Message()
        {
            MessageBox.Show("This is a test command!");
        }
    }
}

ShowMessage 类:

using CommandTestProject.ViewModel;
using System;
using System.Windows.Input;

namespace CommandTestProject.Commands
{
    public class ShowMessage : ICommand
    {
        private ViewModelMsg viewModel;
        public event EventHandler CanExecuteChanged;
        public ShowMessage(ViewModelMsg vm)
        {
            viewModel = vm;
        }

        public bool CanExecute(object parameter)
        {
            return true;
        }

        public void Execute(object parameter)
        {
            viewModel.Message();
        }
    }
}

【问题讨论】:

    标签: c# wpf binding icommand


    【解决方案1】:

    在您的视图模型中,将 internal ICommand MessageCommand 更改为 public ICommand MessageCommand 即可。绑定到内部属性不起作用,因为绑定由位于单独程序集 (PresentationFramework.dll) 中的绑定引擎解析

    【讨论】:

    • 看准了!谢谢!
    猜你喜欢
    • 2020-08-11
    • 1970-01-01
    • 1970-01-01
    • 2017-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多