【问题标题】:Get current Text of editable ComboBox in .NET 4在 .NET 4 中获取可编辑组合框的当前文本
【发布时间】:2013-07-17 08:58:46
【问题描述】:
在 .NET 3.5 中,我有一个实现,它可以像这样获取组合框的当前编辑文本:
dependencyObject.GetValue(ComboBox.TextProperty);
一切正常,值是 ComboBox.Text-Property 上已编辑的文本。现在我们升级到 .NET 4,返回值是旧文本,而不是编辑后的文本,这是第一个奇怪的行为。但是如果 ComboBox 的前一个值是来自 ComboBox.ItemsSource 的项,则上面的代码将返回编辑后的值。目前我不知道微软在 .NET 4 中对该属性进行了哪些更改。有人知道现在有什么不同吗?
【问题讨论】:
标签:
c#
wpf
binding
combobox
【解决方案1】:
尝试像这样使用Text 属性:
XAML
<ComboBox Name="MyComboBox" IsEditable="True" IsTextSearchEnabled="True" SelectedIndex="0" Width="150" Height="30">
<ComboBoxItem>3</ComboBoxItem>
<ComboBoxItem>2</ComboBoxItem>
<ComboBoxItem>4</ComboBoxItem>
<ComboBoxItem>6</ComboBoxItem>
</ComboBox>
<Button Width="100" Height="30" Content="GetEditedText" VerticalAlignment="Bottom" Click="Button_Click" />
Code behind
private void Button_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show(MyComboBox.Text.ToString());
}
或者通过模板访问TextBox:
private void Button_Click(object sender, RoutedEventArgs e)
{
TextBox input = ((TextBox)MyComboBox.Template.FindName("PART_EditableTextBox", MyComboBox));
MessageBox.Show(input.Text.ToString());
}