问题描述
大家好
我的项目遇到了一些奇怪的问题.
在我的应用程序中,我使用类初始化了组合框.按预期工作.
Hi all
I faced some odd problem in my project.
In my application I initialize combobox with my classes. Works as expected.
foreach (MyClass c in Classes)
{
myComboBox.Items.Add(c);
}
我的应用程序中有处理这些类的事件,并且我希望组合框自动选择该类作为selecteditem.当我调试我的应用程序时,它看起来不错,正确的类进入了组合框,但是selecteditem仍然为null,因此ui显示为空的组合框.
这是我的活动的摘要..
I have event in my app which handles those classes and I want combobox select automatically that class as selecteditem. When I debug my app it looks fine, right class goes into combobox, but selecteditem remains null and therefore ui shows empty combobox.
here is snippet of my event..
Event(object sender, EventArgs e)
{
.
.
myComboBox.SelectedItem = e.MyClass; //looks right when debugging, but doest work in Ui side
.
.
}
奇怪的是,组合框无法处理此问题,因为它已经在其中初始化了该类.
希望你有主意:)
干杯!
its odd that combobox cannot handle this because it has that class already initialized in it.
Hope you got idea :)
Cheers!
推荐答案
myComboBox.DataContext=Classes;
它是这样的:
It goes like this:
<combobox name="myCombobox" itemssource="{Binding}">
<combobox.itemtemplate>
<datatemplate>
<textblock text="{Binding Path=Yourproperty}" />
</datatemplate>
</combobox.itemtemplate>
</combobox>
其中您的财产"是该类的属性,将显示其值.
或者您也可以直接将DisplayMemerBinding设置为ComboBox:
where "Yourproperty" is the property of that class whose value is to be displayed.
or you can also set the DisplayMemerBinding directly to the ComboBox :
<combobox name="Acombo" itemssource="{Binding}" displaymemberbinding="{Binding Path=Yourproperty}" />
这篇关于WPF组合框selecteditem问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!