
[英]TextChanged or ContentChanged event in a custom control extending UserControl WPF
[英]WPF Custom Textbox control within UserControl RelativeSource causing TextChanged event to fire even after loaded [closed]
我在 XAML 中定义了一个自定义用户控件,如下所示:
<UserControl x:Class="MyUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:MyApplicationName"
xmlns:wpf="clr-namespace:LibVLCSharp.WPF;assembly=LibVLCSharp.WPF"
mc:Ignorable="d"
>
在其中,我有一个自定义文本框控件,称为 CustomIndicator,它在代码隐藏中继承 TextBox,放置在 XAML 中,如下所示:
<local:CustomIndicator x:Name = "Parameter1" Background="{Binding ElementName=Parameter1, Path=OffColor}" Text="{Binding myUserParameter1, StringFormat=N1, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, RelativeSource={RelativeSource AncestorType={x:Type UserControl}, Mode=FindAncestor}}" OnText="1" OffText="1" ModuleKey="D1" ModuleName="1" Height="20"/>
加载用户控件后,在 Me.Loaded 中,我循环遍历所有控件并向 CustomIndicator 添加一个 TextChanged 处理程序(回想一下,它是一个自定义文本框控件),如下所示:
AddHandler TryCast(ctrl, TextBox).TextChanged, Sub(sender, e) ControlValueChanged(sender, e)
我很肯定它是在 A) 用户控件被初始化/加载和 B) 自定义文本框控件 CustomIndicator 被初始化/加载之后添加的......我在添加处理程序时放置了一个断点并确认两者都是 IsInitialized /IsLoaded=真。 但是,TextChanged 事件仍在触发,因为绑定似乎还在稍后发生。 如果我将 XAML 更改为此,它不会触发,但我也没有得到值:
<local:CustomIndicator x:Name = "Parameter1" Background="{Binding ElementName=Parameter1, Path=OffColor}" Text="{Binding myUserParameter1, StringFormat=N1, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" OnText="1" OffText="1" ModuleKey="D1" ModuleName="1" Height="20"/>
删除“RelativeSource={RelativeSource AncestorType={x:Type UserControl}, Mode=FindAncestor}”使 TextChanged 停止触发延迟,但我也没有得到值。 如何添加处理程序,使其真正在加载所有内容(包括绑定)之后?
顺便说一句,运行跟踪确实揭示了以下内容:
System.Windows.Data Information: 10 : Cannot retrieve value using the binding and no valid fallback value exists; using default instead. BindingExpression:Path=myUserParameter1; DataItem=null; target element is 'CustomIndicator' (Name='Parameter1'); target property is 'Text' (type 'String')
不知道跟踪是否有帮助...但我还要提到 myUserParameter1 的值是 0(或其他一些数值,在主窗口的 Loaded="Window_Loaded" 事件中设置),并且在 Me.Loaded 事件结束时,文本框仍为空白。
虽然它并没有真正解决,但我找到了一个有效的解决方案。 我做的两件事是 1) 在我的绑定中添加了一个 FallbackVaue,以及 2) 更改了用户控件实例创建和值更新的顺序。 虽然这两件事并不能完全解释发生了什么,但它们足以提供所需的功能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.