代码之家  ›  专栏  ›  技术社区  ›  Matt Mitchell

WPF动态设置单元格样式

  •  0
  • Matt Mitchell  · 技术社区  · 14 年前

    但是,此网格的列和样式规则(例如,“如果值低于零则为红色”)在编译时是未知的。

    像这样的问题有上百个,我一定读过其中的一半,但我找不到解决这个问题的方法,这在WinForms中是微不足道的。

    通过设置ListView的ItemContainerStyle,我成功地设置了整行的样式,但是我无法使它集中在单个单元格上。

    {"Child with Name '{x:Type ListViewItem}' not found in VisualTree."} )当然,当我使用DisplayMemberBinding时,CellTemplate根本就不会被调用。

    我的转换器在传递值时,得到的是整行,而不仅仅是单元格的值,所以这可能是有用的信息。

     GridView viewLayout = new GridView();
     for (int i=0; i<columns.Length; i++)
     {
        ColumnDisplaySettings col = columns[i];
        var g = new GridViewColumn() 
        { 
            Width = col.Width, 
            //DisplayMemberBinding = "[" + i + "]" /* Have to omit this for CellTemplate */
        };
    
        if (i == 0)
        {
           g.CellTemplate = new DataTemplate();
           var t = new DataTrigger();
           t.Binding = new Binding("[0]");
           t.Value = "0";
           var b = new Binding() { Converter = new MyBkColorConverter() };
           t.Setters.Add(new Setter(Control.BackgroundProperty, b,
              "{x:Type ListViewItem}")); /* Error here */
           g.CellTemplate.Triggers.Add(t);
        }
    
         viewLayout.Columns.Add(g);
     }
     lv.View = viewLayout;
    

    我在搜索中遇到过datatemplateselector,因此如果在没有任何已知XAML的情况下使用它们有一个有用的参考,那么我也会非常感激。

    谢谢你的帮助。

    2 回复  |  直到 14 年前
        1
  •  0
  •   Kieren Johnstone    14 年前

    发生错误的原因是“{x:Type ListViewItem}”是字符串。{x:..}表示法是一个XAML标记扩展,但您没有使用XAML。要在代码中引用列表ListViewItem,请使用 typeof(ListViewItem) .

    另外,您正在尝试将Background属性设置为类型ListViewItem,这没有什么意义。。让我重新阅读并更新这个答案。。

        2
  •  0
  •   Matt Mitchell    14 年前

    使用WPF工具包的DataGrid是解决这个问题的一种方法(如果需要更多细节,请发表评论)。