扩展 UserControl WPF 的自定义控件中的 TextChanged 或 ContentChanged 事件

TextChanged or ContentChanged event in a custom control extending UserControl WPF

我想更改开源应用程序中的自定义控件。

XAML 看起来像这样:

<controls:Scratchpad Grid.Row="1" Grid.Column="2"
                         Text="{Binding DataContext.KeyboardOutputService.Text, RelativeSource={RelativeSource AncestorType=controls:KeyboardHost}, Mode=OneWay}"/>

Scratchpad 控件的代码隐藏如下所示:

public class Scratchpad : UserControl
{
    public static readonly DependencyProperty TextProperty =
        DependencyProperty.Register("Text", typeof (string), typeof (Scratchpad), new PropertyMetadata(default(string)));

    public string Text
    {
        get { return (string) GetValue(TextProperty); }
        set { SetValue(TextProperty, value); }
    }
}

我想在每次 UserControl 中的文本更改时触发一个事件处理程序。但是,没有我可以在 XAML.

中使用的 TextChanged 事件

我的计划是做这样的事情:

<controls:Scratchpad Grid.Row="1" Grid.Column="2"
                         Text="{Binding DataContext.KeyboardOutputService.Text, RelativeSource={RelativeSource AncestorType=controls:KeyboardHost}, Mode=OneWay}"
                         textChanged="EventHandler"/>

但是 "textChanged" 事件在此自定义控件中不存在。

如您所见,ScratchPad 扩展了 UserControl。 UserControl 还扩展了 ContentControl,这就是为什么我认为可以在此控件中放置文本,它们可能是我不知道的 "ContentChanged" 事件。

最好的,彼得。

两个选项:

  1. (MVVM 方式)如果更改是为了反映域模型中的某些内容,也许此更改最适合在您的视图模型中处理

  2. (控制方式)你考虑过在你的 DependencyProperty 中放置一个改变的处理程序吗?

    public static readonly DependencyProperty TextProperty = DependencyProperty.Register(nameof(Text), typeof(string), typeof(ScratchPad), new PropertyMetadata(null, OnTextChanged));
    
    private static void OnTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        // Handle change here
    }
    

非常感谢 Eric 的回答。

我最终在 "KeyboardOutputService.Text" 的 Setter 中添加了一行额外的代码。但是,如果我要添加一个 OnTextChanged 事件处理程序,我会尝试您的方法。以后我可能会 运行 遇到同样的问题,所以我会继续讨论这个话题。

非常感谢。