开发者

WPF Styling a Cell Dynamically

I have a requirement to generate a "report" in WPF which is simply a grid.

However, the columns and the styling rules (e.g. "Red if value below zero") for this grid are unknown at compile time.

There are hundreds of questions like this and I must have read over half of them but I cannot find a solution to this requirement which would be trivial in WinForms.

I have managed to style an entire row by setting the ItemContainerStyle of the ListView, but I couldn't manage to get this to focus on a single cell.

As such I'm now trying the CellTemplate approach but this throws an error ({"Child with Name '{x:Type ListViewItem}' not found in VisualTree."}) and of course when I use a DisplayMemberBinding the CellTemplate isn't even called at all.

My converter when it gets passed the value is getting the entire row, not just the cell's value, so perhaps this is useful information.

 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 =开发者_C百科 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;

I've encountered DataTemplateSelectors in my searches, so if a useful reference exists on using these without any known XAML then I'd appreciate that too.

Thanks for any help you can provide.


The error is happening because "{x:Type ListViewItem}" is a string. The {x:..} notation is a XAML markup extension, but you're not using XAML. To refer to the list ListViewItem in code, use typeof(ListViewItem).

Oh also, you're trying to set the Background property to a type, ListViewItem, which makes little sense.. let me re-read and update this answer..

Update: you don't need the third parameter to the Setter constructor.

Hope that helps!


Using the WPF Toolkit's DataGrid is one solution to this. (Comment if more details required).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜