【发布时间】:2011-04-03 14:31:42
【问题描述】:
我正在学习如何制作 Visual Studio 样式的属性网格。我有一个 2 列的 GridView,当前将 OK 绑定到具有两个字符串成员的对象列表。目前很好。我希望第二列使用文本输入框,以便我可以更新这些值。 我在网上广泛查看,但只能找到 XAML 示例。到目前为止我得到的(不工作,只显示不可编辑的文本)......
GridView gv = new GridView();
View = gv;
// First Collumn - Name.
GridViewColumn col = new GridViewColumn();
col.Header = "Property";
col.Width = 100;
col.DisplayMemberBinding = new Binding("Name");
gv.Columns.Add(col);
// 2nd Column - Value.
col = new GridViewColumn();
col.Header = "Value";
col.Width = 100;
col.DisplayMemberBinding = new Binding("DefaultValue");
FrameworkElementFactory txt = new FrameworkElementFactory(typeof(TextBox));
txt.SetBinding(TextBox.TextProperty, new Binding()); // sets binding
// add textbox template
col.CellTemplate = new DataTemplate(typeof(string));
col.CellTemplate.VisualTree = txt;
gv.Columns.Add(col);
【问题讨论】:
-
哎呀,后面有这么多代码,你为什么要这样做?使用 XAML 有什么问题?
-
它可能最终会成为 XAML,但我很固执,也想学习如何在代码隐藏中做到这一点。我正在重新面对一个 C++ MFC 应用程序,因此在某些情况下,我不得不比在“纯”WPF 设计中更多地使用代码。
-
XAML 标记非常有用,它可以为您节省大量工作,而且它更短且不易出错。尤其是当涉及到模板代码时,这是一个真正的痛苦,因为您必须使用
FrameworkElementFactories,而在 XAML 中它与声明普通控件没有任何不同。 -
谢谢大家!,我确实喜欢使用 XAML,但我是 WPF 新手,所以当我掌握它时,您会理解我倾向于“在代码中思考”。跨度>
-
“你为什么要这样做?使用 XAML 有什么问题?” – 如果我在不事先知道绑定的情况下动态创建列,情况如何?