无法在wpf文本框中显示组合框的文本

时间:2019-02-16 16:14:32

标签: c# wpf visual-studio combobox

嗨,我使用此代码

private void combobox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    text_f1.text = combobox1.Text;
}

我的第一个记录是“汽车” 第二个记录是“电话” ...

当我选择“汽车”时,首先显示“ car”时不显示任何内容

总是落后一些

出现此问题后,我尝试使用此代码

text_f1.text = combobox1.DisplayMemberPath;

告诉我

"MahName"

错了

我该怎么办?

3 个答案:

答案 0 :(得分:1)

您可以使用 ElementBinding XAML 中轻松实现。

<ComboBox x:Name="comboBox"/>
<TextBlock Text="{Binding Path=SelectedItem.MahName, ElementName=comboBox}"/>

答案 1 :(得分:-1)

我认为您应该使用SelectedIndexChanged事件而不是SelectionChanged。您的第一个代码应与此事件一起使用。

答案 2 :(得分:-1)

combobox1.Text是组合框的可编辑文本(当选择更改时,它会滞后一点)。确切的解决方案取决于组合框包含哪些项目以及如何配置。

如果它包含字符串,则可以编写

text_f1.Text = (string)combobox1.SelectedItem;

如果它包含类Article的对象(例如),则可以使用

if (combobox1.SelectedItem is Article article) {
    text_f1.Text = article.MahName;
}

或者如果项目的ToString方法已被覆盖

if (combobox1.SelectedItem != null) {
    text_f1.Text = combobox1.SelectedItem.ToString();
}

text_f1.Text = combobox1.SelectedItem?.ToString();

如果没有选定的项目,则最后一个版本将null分配给text_f1。参见:?. and ?[] null-conditional operators