[英]How to display the selection of a ComboBox with a list fetched from a database in WPF
I have a ComboBox which the ItemSource is binded to a List of ESTADO
, a entity in my project.我有一个 ComboBox,它的 ItemSource 绑定到一个 List of
ESTADO
,这是我项目中的一个实体。 The ComboBox look like this:组合框看起来像这样:
<ComboBox Style="{StaticResource ComboBoxStyle}" Visibility="{Binding EstadoComboBox}" Name="CatalogoEstados" DisplayMemberPath="NOMBRE" SelectedValuePath="NOMBRE" SelectedValue="{Binding Estado}" ItemsSource="{Binding Estados}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="SelectionChanged">
<i:InvokeCommandAction Command="{Binding SeleccionarEstadoCommand}" CommandParameter="{Binding ElementName=CatalogoEstados, Path=SelectedItem.ID}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</ComboBox>
When I select a item in the ComboBox, the property NOMBRE
of the object ESTADO
who is a string is assigned to a variable of type string named Estado
.当我在 ComboBox 中选择一个项目时,作为字符串的对象
ESTADO
的属性NOMBRE
被分配给名为Estado
字符串类型变量。
Somethimes I want the variable Estado
to be assigned from the constructor like this:有时我希望像这样从构造函数分配变量
Estado
:
Estado = pplDatosGenerales.ESTADO;
pplDatosGenerales.ESTADO
is a string with the string item previously select in the ComboBox, but when I assign the variable from the constructor, the ComboBox view is not showing the item selected, the variable is assigned correctly but in the view the ComboBox appears empty as if I haven't selected anything. pplDatosGenerales.ESTADO
是一个字符串,其中包含先前在 ComboBox 中选择的字符串项目,但是当我从构造函数分配变量时,ComboBox 视图未显示所选项目,变量已正确分配,但在视图中 ComboBox 显示为空如果我没有选择任何东西。 Why is this happening and how can I solve this?为什么会发生这种情况,我该如何解决? I want the ComboBox to show the value that the variable
Estado
has.我希望 ComboBox 显示变量
Estado
具有的值。
You're going to have to post more of your code.您将不得不发布更多代码。 You've set
SelectedValuePath
to NOMBRE...if NOMBRE is a string then your SelectedValue
type should be a string too, but you're instead binding it to a view model property called Estado?您已将
SelectedValuePath
设置为 NOMBRE...如果 NOMBRE 是一个字符串,那么您的SelectedValue
类型也应该是一个字符串,但您将其绑定到名为 Estado 的视图模型属性? In which case Estado should be a string too, and in your constructor you would instead do `Estado = pplDatosGenerales.ESTADO.NOMBRE'.在这种情况下,Estado 也应该是一个字符串,而在您的构造函数中,您将改为执行 `Estado = pplDatosGenerales.ESTADO.NOMBRE'。
I suspect the problem here is simply the SelectedValuePath
setting.我怀疑这里的问题只是
SelectedValuePath
设置。 Remove it, and you'll probably find that this all starts working as you intend.删除它,您可能会发现这一切都按您的意愿开始工作。
This was happening because the value of Estado was not in the ComboBox ItemSource.这是因为 Estado 的值不在 ComboBox ItemSource 中。 Once I debugged the project and saw the value of Estado was not included in the ItemSource.
一旦我调试了项目并看到 Estado 的值未包含在 ItemSource 中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.