Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to programatically add a binding converter to a WPF ListView?

Tags:

c#

listview

wpf

I am having a lot of trouble finding a good example of how to programatically create, fill and style a ListView. Every example I find tends to use a lot of XAML markup and a minimum amount of C# to switch which bit of markup is being run. This is impossible for me as I do not know the composition of the columns, nor the intended styles, at compile time.

What I need is pretty trivial - a ListView where a particular cell for a given row will be red if the value is negative, or black of the value is positive. However, which row this is and what colours it will be are not known until runtime (an example that is dynamic/programatic will be sufficient).

What I have (simplified) is something like this:

string[] columns = new string[] { "Test", "Test2" };
ListView lv = new ListView();

/* Add Columns (works */
GridView viewLayout = new GridView();
foreach (string colName in columns)
{
    viewLayout.Columns.Add(new GridViewColumn{ Header = colName });
}
lv.View = viewLayout;

/* Add Items (happy to go the .source path if it's easier) */
foreach (object d in GetData())
{
     lv.Items.Add(d);
}

/* Example style, fails */
lv.ItemContainerStyle.Setters.Add(
 new Setter(Control.BackgroundProperty, *how do you connect the IValueConverter*)
);
like image 559
Matt Mitchell Avatar asked Jul 07 '10 09:07

Matt Mitchell


1 Answers

Use a Binding, set the Converter property ;)

new Binding() { Converter = new MyAwesomeConverter() }
like image 57
Arcturus Avatar answered Nov 09 '22 03:11

Arcturus