【问题标题】:Set Custom Commands to programmatically created Buttons将自定义命令设置为以编程方式创建的按钮
【发布时间】:2013-09-27 22:37:14
【问题描述】:

我是 WPF 新手,我正在尝试创建一个从 XML 文件构建自身的接口。新构建的界面包含不同的控件,如文本框、标签或按钮。最后一个让我头疼了好几天,因为每个按钮都有自己的命令。

按钮的示例 XML 代码:

ID="1001" GroupID="1" Control="Button" Content="Apply" Margin="2" Width="60"

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

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;
}

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

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

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

感谢任何提示。

【问题讨论】:

  • 你最终想要完成什么?您是否尝试从 xml 动态构建 UI?
  • 如何在 setCommands() 中设置按钮上的命令?
  • @Omribitan:是的,这就是背后的想法。
  • @nit:这就是问题所在。方法应该可以,但是不知道怎么做。
  • 如果你这样做是为了序列化/反序列化,你可以使用XamlWriter 这样做,虽然我应该注意你不应该序列化 UI

标签: c# wpf mvvm commandbinding


【解决方案1】:

首先,如果您定义了要绑定到 UI 上的按钮的自己的命令,那么它们应该通过 UI 的 public properties in your VM or DataContext 公开。

然后,一旦你有了这个安排,你可以像下面这样设置命令按钮:

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

【讨论】:

  • 工作正常!在对 DataContext 进行一些解决后,它会做它应该做的事情。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-05-12
  • 1970-01-01
  • 2018-01-14
  • 2015-02-04
  • 2017-12-06
  • 2016-08-01
  • 1970-01-01
相关资源
最近更新 更多