简体   繁体   中英

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

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*)
);

使用Binding,设置Converter属性;)

new Binding() { Converter = new MyAwesomeConverter() }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM