【问题标题】:AutoCompleteBox.Text property is behaving weirdAutoCompleteBox.Text 属性的行为很奇怪
【发布时间】:2014-04-18 13:22:43
【问题描述】:

我遇到了一个奇怪的问题。 我的视图中有一个 AutoCompleteBox

<sdk:AutoCompleteBox x:Name="txtSIA" 
 Grid.ColumnSpan="1" Grid.Row="1" Grid.Column="1"
 SelectedItem="{Binding SIA, Mode=TwoWay, ValidatesOnNotifyDataErrors=True}" 
 Text="{Binding TextSIA, Mode=TwoWay}"
 KeyUp="TxtSIA_KeyUp"
 Populating="SIANonSIU_Populating" 
 Style="{StaticResource AutoCompleteStyle}"  
/>

我实现了一个字段验证器,用于检查其文本是否为空或空字符串。 它工作得很好,但棘手的部分是我有一个重置所有控件值的按钮,我的视图模型中的代码是:

void BtnReset_OnClick(RoutedEventArgs e)
{
    SIA = new SIA();
    TextSIA = string.Empty;
    BtnGeneralIsEnabled = false;
    DataGridSource = null;
}

每当我单击它然后在我的 AutoCompleteBox 中写入时,AutoCompleteBox 永远不会为空或 null,即使在我的代码后面的按键事件侦听器中也是如此。

这里有一些图片来说明我的观点:

【问题讨论】:

    标签: c# .net binding autocompletebox


    【解决方案1】:

    注册到 AutoCompleteBox 的 TextChanged 事件而不是 KeyUp:

    “当 AutoCompleteBox 的文本框部分中的文本发生更改时发生。”

    【讨论】:

    • 尝试通过 e.Source 而不是 sender 投射 TextBox。 TextSIA 属性是否实现了 INotifyPropertyChanged?
    • 仍然没有修复它。真正的交易是它工作正常,除了点击重置按钮之后..
    【解决方案2】:

    我找到了答案here

    要解决这个问题,我们必须创建一个新的自动完成框并覆盖 OnApplyTemplate 方法。

    public class CustomAutoComplete : AutoCompleteBox
    {
    TextBox mytext;
    
    public override void OnApplyTemplate()
    {
        base.OnApplyTemplate();
        mytext = GetTemplateChild("Text") as TextBox;
        mytext.TextChanged += new System.Windows.Controls.TextChangedEventHandler(mytext_TextChanged);
    }
    
    void mytext_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
    {
        this.Text = mytext.Text;
        OnTextChanged(new RoutedEventArgs());
    }
    

    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多