Note that there are some explanatory texts on larger screens.

plurals
  1. POWPF - Set DataTemplate for programmatically added GridViewColumns
    text
    copied!<p>Couldn't find an answer to this one.</p> <p>I have a WPF ListView control that can contain varying number of columns. For example, it can display customer data, displaying columns Id, Name, Email etc, or it can contain products, displaying ID, Name, Price, NumberInStock, Manufacturer, well, you get the idea: varying number of columns, varying names.</p> <p>What I want to do, is for certain columns to display the data differently. For example, instead of printing 'Yes' or 'No' as the value of the column NumberInStock, I want to display a neat image.</p> <p>If I'd have a fixed amount of columns, with fixed names to bind to, I kinda see how this is easy. Just define a DataTemplate for that particular column and I'd use that to define the view of my column. However, I can't see how to do it in my situation.</p> <p>I am very new to WPF, so excuse me if my approach is bad :-) In my XAML, I have defined a ListView control, which is pretty much empty. In my code behind, I use:</p> <pre><code> // get all columns from my objects (which can be either a Customer of Product) foreach (string columnName in MyObject.Columns) { GridViewColumn column = new GridViewColumn(); // Bind to a property of my object column.DisplayMemberBinding = new Binding("MyObject." + columnName); column.Header = columnName; column.Width = 50; // If the columnname is number of stock, set the template to a specific datatemplate defined in XAML if (columnName == "NumberInStock") column.CellTemplate = (DataTemplate)FindResource("numberInStockImageTemplate"); explorerGrid.Columns.Add(column); } </code></pre> <p>Ok, I'm sure this could be done a bit prettier (if you have any advice, please!) but the biggest problem is that I can't see any difference in the column. It just displays the text value of the 'NumberInStock' column. My DataTemplate is defined in the XAML:</p> <pre><code>&lt;Window.Resources&gt; &lt;DataTemplate x:Name="NumberInStock" x:Key="NumberInStock"&gt; &lt;Border BorderBrush="Red" BorderThickness="2.0"&gt; &lt;DockPanel&gt; &lt;Image Width="24" Height="24" Margin="3,0" Source="..\Images\instock.png" /&gt; &lt;/DockPanel&gt; &lt;/Border&gt; &lt;/DataTemplate&gt; &lt;/Window.Resources&gt; </code></pre> <p>Of course, I would still have to add the functionality that it would display a 'yes' or 'no' image depending on the value of NumberInStock, but that is step 2 really. I would be happy to see an image and a red border in my ListView!</p> <p>Thanks in advance, Razzie</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload