【问题标题】:TextChanged event on user control being called before dependency property setter is accessed在访问依赖属性设置器之前调用用户控件上的 TextChanged 事件
【发布时间】:2012-05-23 13:56:23
【问题描述】:

在使用自定义用户控件之前,我使用的是标准文本框,文本属性绑定到列表框中所选项目的属性。该绑定还使用了验证规则。设置此属性后,在 xaml 中触发了文本更改事件,一切正常。

现在我已将其更改为使用包含文本框的用户控件。我向绑定到文本框的文本属性的用户控件添加了一个依赖属性。现在,在验证发生之前更改文本时会触发该事件。在我的对话框中绑定到同一项目的另一个属性的复选框被选中之前,不会发生验证。除了在列表框中的初始选择之外,我的模型视图中的 set 方法上的断点不再被破坏,但是当我在单击文本框后看到效果时,值正在更新。在单击复选框之前,我的验证显示的错误消息不会出现。

我的窗口中用户控件的 XAML:

<my:BoundTextBox x:Name="spacingValueBox" TextBoxBase.TextChanged="spacingValueBox_TextChanged">
    <my:BoundTextBox.Text>
       <Binding Path="SelectedItem.Property" UpdateSourceTrigger="PropertyChanged" Mode="TwoWay">                                       
           <Binding.ValidationRules>
              <validators:ValidationRule ErrorMessage="Invalid"/>
           </Binding.ValidationRules>
      </Binding>
   </my:BoundTextBox.Text>

在 XAML 中绑定到我的用户控件的 Text 属性:

<UserControl x:Class="ButtonTextBox" ...
         ... Name="control">
<TextBox Text="{Binding Text, ElementName=control}"/>

依赖属性:

public static readonly DependencyProperty TextProperty =
TextBox.TextProperty.AddOwner(typeof(BoundTextBox));

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

【问题讨论】:

  • 我看到你必须在依赖属性上注册事件。但是我似乎不能这样做并将我的控件添加到 text 属性的所有者?

标签: c# .net wpf user-controls dependency-properties


【解决方案1】:

解决方案实际上非常简单,我只需将 UpdateSourceTrigger 值设置为 PropertyChanged

<TextBox Text="{Binding Text, ElementName=control, UpdateSourceTrigger=PropertyChanged}"/>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-31
    • 1970-01-01
    • 1970-01-01
    • 2020-08-08
    相关资源
    最近更新 更多