将自定义命令设置为以编程方式创建的按钮

Syn*_*ynn 1 c# wpf mvvm commandbinding

我是WPF的新手,并尝试创建一个从XML文件构建自己的接口.新构建的界面包含不同的控件,如文本框,标签或按钮.最后一个让我头疼几天,因为每个按钮都会得到自己的命令.

按钮的示例XML代码:

ID="1001" GroupID="1" Control="Button" Content="Apply" Margin="2" Width="60"
Run Code Online (Sandbox Code Playgroud)

这是定义每个按钮的方法:

public Button Button(XElement xElement, Button newButton)
{
    if (xElement.Attribute("Width") != null)
        newButton.Width = Convert.ToDouble((xElement.Attribute("Width").Value));

    if (xElement.Attribute("Content") != null)
    {
        string sContent = xElement.Attribute("Content").Value;

        //Here gets the button its command
        Commands Commands = new Commands();
        Commands.setCommand(sContent, newButton);
        newButton.Content = sContent;
    }
    return newButton;
}
Run Code Online (Sandbox Code Playgroud)

内容属性同时命名按钮和功能.

问题:基本上我尝试构建一个包含所有可能命令的命令类.每次创建按钮时,该setCommand(sContent, newButton)方法都会扫描commands该类,并通过Switch-Case语句将匹配命令设置为此按钮.

现在,每次单击按钮时,都会触发分配的命令.但这样做甚至可能这样做,还是我走错了路?有没有更简单的解决方案来做到这一点,还是我只是缺少命令绑定的基本要素?

任何提示都表示赞赏.

Nit*_*tin 5

首先,如果您定义了自己的命令,并希望绑定到UI上的按钮,则应通过public properties in your VM or DataContextUI 公开它们.

然后,一旦你有这样的安排,你可以设置如下按钮上的命令:

Binding binding = new Binding();
binding.Path = new PropertyPath("MyCommand"); //Name of the property in Datacontext
button.SetBinding(Button.CommandProperty, binding);
Run Code Online (Sandbox Code Playgroud)