【发布时间】: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