ListView databinding to display usercontrols
My goal is to add different Controls/UserControls in a WPF ListView. The Controls can be of any types. Here is an example of what it would look like with 3 different Controls/UserControls:
WHAT WORKS
This would work if I use the following XAML and code:
<ListView Name="ControlsListView">
<ListView.View>
<GridView>
<GridViewColumn Header="Control"/>
</GridView>
</ListView.View>
</ListView>
Here is the code:
ObservableCollection<Control> Controls { get; set; }
//...
ControlsListView.ItemsSource = Controls;
//...
Controls.Add(new ThresholdControl());
Controls.Add(new CheckBox());
Controls.Add(new Button()
{
Content = "Test"
});
WHAT DOESN'T WORK
My problem is when I want to add a level of indirection in the ObservableCollection. Instead of using directly a collection of Control, I would like to have a collection of MyItem. MyItem would开发者_运维百科 itself contain the Control to display. Something like this:
class MyItem
{
public Control MyControl { get; set; }
}
ObservableCollection<MyItem> Controls { get; set; }
And I would bind my ListView like this:
<GridViewColumn Header="Control" DisplayMemberBinding="{Binding MyControl}"/>
When displaying a string, this will work ok, but for displaying a Control, this won't work. In fact, in my example, it would display the string representing the class of the Control inserted in the list instead of the Control itself.
What do I need to do to bind to the Controls in my list? DisplayMemberBinding doesn't seem to be the good choice here.
Thanks!
You want to use the CellTemplate property instead of DisplayMemberBinding. You can then have your CellTemplate display the control you want. I think the code would look something like this:
<ListView Name="ControlsListView">
<ListView.View>
<GridView>
<GridViewColumn Header="Control">
<GridViewColumn.CellTemplate>
<DataTemplate>
<ContentControl Content={Binding MyControl} />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
精彩评论