ListView 数据绑定以显示用户控件
我的目标是在 WPF ListView 中添加不同的控件/用户控件。控件可以是任何类型。下面是 3 个不同的控件/用户控件的示例:
什么有效
如果我使用以下 XAML 和代码,这将有效:
<ListView Name="ControlsListView">
<ListView.View>
<GridView>
<GridViewColumn Header="Control"/>
</GridView>
</ListView.View>
</ListView>
这是代码:
ObservableCollection<Control> Controls { get; set; }
//...
ControlsListView.ItemsSource = Controls;
//...
Controls.Add(new ThresholdControl());
Controls.Add(new CheckBox());
Controls.Add(new Button()
{
Content = "Test"
});
什么不起作用
我的问题是当我想添加间接级别时在可观察集合中。我不想直接使用 Control 的集合,而是希望拥有 MyItem 的集合。 MyItem 本身包含要显示的控件。像这样的东西:
class MyItem
{
public Control MyControl { get; set; }
}
ObservableCollection<MyItem> Controls { get; set; }
我会像这样绑定我的 ListView:
<GridViewColumn Header="Control" DisplayMemberBinding="{Binding MyControl}"/>
当显示字符串时,这可以正常工作,但是当显示控件时,这将不起作用。事实上,在我的示例中,它将显示表示插入列表中的控件类的字符串,而不是控件本身。
我需要做什么才能绑定到列表中的控件? DisplayMemberBinding 在这里似乎不是一个好的选择。
谢谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您想要使用 CellTemplate 属性而不是 DisplayMemberBinding。然后您可以让 CellTemplate 显示您想要的控件。我认为代码看起来像这样:
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: