【问题标题】:Changing Text Binding on User Control fires text changed event but doesnt detect the new text更改用户控件上的文本绑定会触发文本更改事件,但未检测到新文本
【发布时间】:2021-09-17 16:54:22
【问题描述】:

我有一个自定义的 WPF 文本框用户控件。我正在写一些内容,但它总是检测到在 XAML 上预设的相同数据,通过执行 textbox.Text get call 不会显示新的书面文本。

public partial class SearchBox : UserControl
{
    public SearchBox()
    {
        InitializeComponent();
        this.DataContext = this;
    }

    private void TextBox_GotFocus(object sender, RoutedEventArgs e)
    {
        if (sender is TextBox textBox && textBox.Tag.ToString() == textBox.Text)
            textBox.Clear();
    }
    private void TextBox_LostFocus(object sender, RoutedEventArgs e)
    {
        if (sender is TextBox textBox && string.IsNullOrEmpty(textBox.Text))
            textBox.Text = textBox.Tag.ToString();
    }

    public string Text { get; set; }

    public event TextChangedEventHandler TextChanged;
    private void TextBox_TextChanged(object sender, TextChangedEventArgs args)
    {
        TextChangedEventHandler h = TextChanged;
        if (h != null)
        {
            h(this, args);
        }
    }
}

它需要如何工作:

<v:SearchBox x:Name="searchBox" TextChanged="searchBox_TextChanged" Text="Input a keyword to filter..." Tag="Input a keyword to filter..." HorizontalAlignment="Left"/>

用户在文本框“test”上写入 --> textbox.Text 返回“输入关键字过滤...”

感谢您的帮助!

【问题讨论】:

  • 你的searchBox_TextChanged函数是什么?

标签: c# textbox textchanged


【解决方案1】:

您的类继承自 UserControl 而不是 TextBox。

虽然您没有为SearchBox 共享您的XAML,但我假设您在其中有一个TextBox,您希望从中获取文本。问题是,属性SearchBox.Text 与SearchBox.TextBox.Text 不同。因此,即使您更改了TextBox 中的文本,SearchBox.Text 仍然保持不变。

解决方案:使用SearchBox.TextBox.Text 作为您的结果。

【讨论】:

  • 这成功了,非常感谢。你有什么想法让它漂亮,所以我可以做 SearchBox.text 来收集文本框文本?
  • 为此,请将SearchBox 更改为从TextBox 继承而不是UserControl。然后将代码中的引用从TextBox 更改为SearchBox。您将不得不重新实现一些事件。
猜你喜欢
  • 2011-01-14
  • 1970-01-01
  • 2010-11-01
  • 2022-11-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多