C# 如何从类似组合框的项[1]中获取文本

C# 如何从类似组合框的项[1]中获取文本,c#,wpf,text,combobox,get,C#,Wpf,Text,Combobox,Get,当我使用这个代码“var z=comboBox.Items[1].ToString();”然后在“MessageBox”中显示z时,我得到了这个消息“DataMdellayer.custumer”,但我想要项目1的文本 <ComboBox x:Name="comboBox" HorizontalAlignment="Left" Margin="57,63,0,0" VerticalAlignment="Top" Width="120"/> 第1项的索引在c#中从零开始,因此请按如

当我使用这个代码“var z=comboBox.Items[1].ToString();”然后在“MessageBox”中显示z时,我得到了这个消息“DataMdellayer.custumer”,但我想要项目1的文本

 <ComboBox x:Name="comboBox" HorizontalAlignment="Left" Margin="57,63,0,0" VerticalAlignment="Top" Width="120"/>

第1项的索引在c#中从零开始,因此请按如下方式更改代码以获得第1项


var z=comboBox.Items[0].ToString()

您正在使用
Customers的
CustomerSay
属性来显示值

当你说:

var z = comboBox.Items[1].ToString();
您正在将
客户
转换为
字符串

但是,考虑到您想要客户的
customersay
属性,您必须寻找它

所以你必须把你的ComboBoxItem投给客户

(Customer)comboBox.Items[1]
然后再找房子

var z = ((Customer)comboBox.Items[1]).CustomerSay

1-您可以将项目强制转换为@Marko所说的数据源对象(客户)

2-使用MVVM并将组合框绑定到ViewModel属性。WPF有强大的绑定系统来实现MVVM

3-您可以重写Customer类的ToString方法:

public class Customer
{
  public override string ToString()
  {
    return CustomerSay;
  }
}

我更喜欢第二种解决方案,但如果您不想使用MVVM模式,那么@Marko的解决方案会更好

分配ItemsSource后,不应访问Items集合。从源集合中获取数据,即
数据库。客户
。也就是说,
((Customer)comboBox.Items[1])。CustomerSay
应该可以工作。感谢兄弟,它可以工作。它没有回答问题,也没有解释他们为什么会收到对象的类型名称,或者如何访问他们需要的文本。
public class Customer
{
  public override string ToString()
  {
    return CustomerSay;
  }
}