【问题标题】:Newbie Using GridView CellTemplate from C#新手使用 C# 中的 GridView CellTemplate
【发布时间】: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 有什么问题?” – 如果我在不事先知道绑定的情况下动态创建列,情况如何?

标签: c# wpf gridview


【解决方案1】:

+1 关于为此使用 XAML 的 cmets,但这并不能回答您的问题。

我怀疑 TextBoxes 是只读的原因是因为您直接绑定到字符串。如果 WPF 允许您编辑它,它会将字符串存储在哪里?如您所知,.NET 中的字符串是不可变的。

试试这个:

class StringContainer
{
     public string SomeValue { get; set; }
} 

现在像这样连接起来:

FrameworkElementFactory txt = new FrameworkElementFactory(typeof(TextBox));
txt.SetBinding(TextBox.TextProperty, new Binding("SomeValue")); // sets binding

// add textbox template
col.CellTemplate = new DataTemplate(typeof(StringContainer));

当你绑定数据时,记得将可编辑的字符串包裹在StringContainer对象中。

myDataRow.DefaultValue = new StringContainer("Some string");

【讨论】:

  • 太棒了!根据需要工作。自我注意:使用 CellTemplate 时,不要同时使用 DisplayMemberBinding(似乎会覆盖/取消 CellTemplate)。
猜你喜欢
  • 2021-03-23
  • 1970-01-01
  • 1970-01-01
  • 2017-01-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-21
  • 2018-01-16
相关资源
最近更新 更多