WPF 中组合框的绑定
我是 wpf 的初学者。实际上,我正在设计一个从数据库接收数据的 ComboBox 样式。 此时,ComboBox
在没有样式的情况下工作正常。
我已经在样式表中编辑了 ComboboxItem
控件的 ControlTemplate
,就像资源字典一样。
如果 Style
适用于具有静态数据的 ComboBox
,则该样式可以正常工作。但是,如果样式应用于具有动态数据的 ComboBox
(在本例中从数据库绑定),则项目列表仅返回对象(显示的项目类似于“Class.Method.Property”),但是不是我需要显示的属性内容。
我一直在尝试一切,并且阅读了互联网上有关 xaml 样式和 ComboBox
模板的所有内容,但我无法解决问题。
我的 ContentPresenter
看起来像这样,它返回数据绑定的对象:
<ContentPresenter
ContentTemplate="{TemplateBinding ContentControl.ContentTemplate}"
Content="{TemplateBinding ContentControl.Content}"/>
有人可以帮助我吗?
I'm a beginner in wpf. Actually I'm styling a ComboBox
which receives data from a database.
The ComboBox
works fine at this point without a style.
I have edited the ControlTemplate
of the ComboboxItem
control in a stylesheet, like a resource dictionary.
If the Style
applies to ComboBox
with static data, the style works fine. But if the style applies to ComboBox
with dynamic data (binding from a database in this case), the items list only returns the object (the items shown is similar to "Class.Method.Property") but not the content of the property that I need to show.
I have been trying all, and I have read everything on the internet about xaml styles and ComboBox
templates but I couldn't solve the problem.
My ContentPresenter
looks like this which returns the object of the databinding:
<ContentPresenter
ContentTemplate="{TemplateBinding ContentControl.ContentTemplate}"
Content="{TemplateBinding ContentControl.Content}"/>
Can anybody help me please?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
显示“Class.Method.Property”是因为 WPF 不知道如何显示您的类。您需要的是适合您的班级的 DataTemplate。
除非您确实需要它,否则我不会像您在示例中那样深入研究模板。
如果您有一个包含对象的数据绑定 ComboBox,并且您只想显示绑定对象的属性,您可以执行以下操作:
如果您想要更高级的显示,您可以设置 ItemTemplate。
"Class.Method.Property" is shown because WPF doesn't know how to do display your class. What you need is a DataTemplate for your class.
Unless you really need it, I wouldn't dig so deep in to the templates as you have in your examples.
If you have a databound ComboBox with objects and you just want to display a property of the bound object you can do:
If you want a more advanced display, you can set the ItemTemplate.
我最近遇到了同样的问题,为了解决它,我的内容演示器现在看起来像这样:
我的问题,很像你的问题,是我缺少 ContentTemplateSelector。另外,如果您也遇到下拉列表显示不正确的问题,我发现在 ComboBoxItem 样式中,您可以将内容演示器留空 (
),它将正确显示。I recently ran into the same issue and to fix it my content presenter now looks like this:
My problem, much like yours, was the fact that I was missing the ContentTemplateSelector. Also if you are having issue with the drop down showing incorrectly as well, I found that in the ComboBoxItem style you can leave the content presenter blank (
<ContentPresenter />
) and it will display properly.