【问题标题】:WPF - GetBindingExpression in PropertyChangedCallback of DependencyPropertyWPF - DependencyProperty 的 PropertyChangedCallback 中的 GetBindingExpression
【发布时间】:2015-04-14 15:24:43
【问题描述】:

我需要能够从 TextBox 的 DependencyProperty 中访问 TextBox 的 Text 属性的绑定表达式。我的 DependencyProperty 的值是在 XAML 中设置的。我在我的 DependencyProperty 的 PropertyChangedCallback 方法中调用 GetBindingExpression,但我现在还为时过早,因为 GetBindingExpression 总是在这里返回 null,但是在窗口完全加载后它肯定会返回一个值(我测试使用屏幕上的一个按钮来更改我的 DependencyProperty 的值)。

显然我在这里有一个加载顺序问题,我的 DependencyProperty 的值是在 Text 属性绑定到我的视图模型之前设置的。我的问题是,是否有一些事件可以用来识别 Text 属性的绑定何时完成?最好不要修改我的 TextBox 的 XAML,因为我在解决方案中有数百个。

public class Foobar
{
    public static readonly DependencyProperty TestProperty =
        DependencyProperty.RegisterAttached(
        "Test", typeof(bool), typeof(Foobar),
        new UIPropertyMetadata(false, Foobar.TestChanged));

    private static void TestChanged(DependencyObject o, DependencyPropertyChangedEventArgs args)
    {
        var textBox = (TextBox)o;
        var expr = textBox.GetBindingExpression(TextBox.TextProperty); 
        //expr is always null here, but after the window loads it has a value
    }

    [AttachedPropertyBrowsableForType(typeof(TextBoxBase))]
    public static bool GetTest(DependencyObject obj)
    {
        return (bool)obj.GetValue(Foobar.TestProperty);
    }

    [AttachedPropertyBrowsableForType(typeof(TextBoxBase))]
    public static void SetTest(DependencyObject obj, bool value)
    {
        obj.SetValue(Foobar.TestProperty, value);
    }
}

【问题讨论】:

  • 你在哪里设置绑定?

标签: c# wpf xaml binding


【解决方案1】:

尝试监听 LayoutUpdated 事件。我认为它称为布局更新事件。否则谷歌它。这是一个疯狂的小事件,无论你做什么,每次都会被解雇。加载、绘图时,甚至移动鼠标!

看看这个伪代码:

private static void TestChanged(DependencyObject o, DependencyPropertyChangedEventArgs args)
    {
        var textBox = (TextBox)o;
        // start listening
        textBox.LayoutUpdated += SomeMethod();
    }

   private static void SomeMethod(...)
   {
      // this will be called very very often
      var expr = textBox.GetBindingExpression(TextBox.TextProperty); 
      if(expr != null)
      {
        // finally you got the value so stop listening
        textBox.LayoutUpdated -= SomeMethod();

【讨论】:

  • 是的,效果很好,谢谢!正如你所说,该事件被称为疯了,所以我会确保在完成我需要做的事情后立即删除监听器。
  • 它只是一个虚拟事件,用于通知您 UI 中的某些内容已更改。删除监听器非常重要。
猜你喜欢
  • 2019-03-22
  • 2011-01-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-16
相关资源
最近更新 更多