如何在WPF中创建类似UserControl的ComboBox
我正在尝试构建一个能够从 XAML 中获取元素的用户控件,如下所示:
<ComboBox >
<ComboBoxItem />
<ComboBoxItem />
<ComboBoxItem />
</ComboBox>
在 ComboBox
中,您只需在 ComboBox
标记之间添加项目,然后我想复制这个,但不知道从哪里开始。
完成后它应该看起来像这样:
<cis:ReportControl Grid.Row="3">
<cis:ReportItem />
</cis:ReportControl>
在 cis:ReportControl 中,有一些 Button
和一个 ComboBox
,基本上我只想提供带有项目的ComboBox
。
报表项只是一个带有一些额外属性的ComboBoxItem
。
编辑:
我已经根据@Snowbears的回答实现了它,但现在的问题是控件本身作为一个项目。 我认为这是因为我有一些内容,并且通过将 ContentProperty
定义到我的 ComboBox
,它被重定向到 Box 中。 我可以做什么来避免这种情况?
编辑 II:
现在可以完全使用此方法:
private ItemCollection reportItems;
public ItemCollection ReportItems
{
get
{
if (reportItems == null)
{
reportItems = this.ComboBoxReports.Items;
}
return reportItems;
}
}
使用 [ContentProperty("ReportItems")]
属性。 ComboBoxReports 是控件中的组合框,我必须继承 ItemsControl
才能使其工作。
I'm trying to build an usercontrol wich is able to take elements from XAML like this:
<ComboBox >
<ComboBoxItem />
<ComboBoxItem />
<ComboBoxItem />
</ComboBox>
In the ComboBox
, you can just add the Items between the ComboBox
tags, and I would like to copy this, but I don't know where to start.
Finished it should look like this:
<cis:ReportControl Grid.Row="3">
<cis:ReportItem />
</cis:ReportControl>
In the cis:ReportControl
, there are some Button
s and a ComboBox
, and basically I only want to feed the ComboBox
with Items.
The Report Item is just a ComboBoxItem
with some extra properties.
Edit:
I've implemented it according to @Snowbears answer, but the problem now is that the control has itself as an item.
I think this is because I have some content, and by defining the ContentProperty
to my ComboBox
, it is redirected into the Box.
What can I do to avoid this?
Edit II:
It fully works now with this:
private ItemCollection reportItems;
public ItemCollection ReportItems
{
get
{
if (reportItems == null)
{
reportItems = this.ComboBoxReports.Items;
}
return reportItems;
}
}
with the [ContentProperty("ReportItems")]
Attribute. ComboBoxReports is the ComboBox in the Control, and I had to inherit from ItemsControl
to get it to work.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
IList
接口的内容。假设此属性将命名为ReportItems
。该属性不应具有设置器,并且应在 UserControl 本身中或在支持字段上的字段初始化的构造函数中进行初始化。ReportItems
)ItemsSource
绑定到 UserControl 的ReportItems
属性IList
interface. Let's say this property will be namedReportItems
. This property should not have setter and it should be initialized in UserControl itself either in constructor in by field initialization on backing field.ReportItems
)ItemsSource
bound to UserControl'sReportItems
property如果您寻找
如何创建自己的控件
,您必须寻找两件事:我认为您可能需要使用自定义控件。您还可以从 ComboBox 或其他控件继承自定义控件。
if you look for
How to Create Your own Control
, You must look for two things:I think you might need to use Custom-Control. Also you can inherit your Custom-Control from
ComboBox
or other Controls.