C# WPF-DependencyProperty的PropertyChangedCallback中的GetBindingExpression
我需要能够从TextBox的DependencyProperty中访问TextBox的Text属性的绑定表达式。my DependencyProperty的值在XAML中设置。我在DependencyProperty的C# WPF-DependencyProperty的PropertyChangedCallback中的GetBindingExpression,c#,wpf,xaml,binding,C#,Wpf,Xaml,Binding,我需要能够从TextBox的DependencyProperty中访问TextBox的Text属性的绑定表达式。my DependencyProperty的值在XAML中设置。我在DependencyProperty的PropertyChangedCallback方法中调用GetBindingExpression,但现在我太早了,因为GetBindingExpression在这里总是返回null,但在窗口完全加载之后,它肯定会返回一个值(我使用屏幕上的按钮更改DependencyProperty
PropertyChangedCallback
方法中调用GetBindingExpression
,但现在我太早了,因为GetBindingExpression
在这里总是返回null,但在窗口完全加载之后,它肯定会返回一个值(我使用屏幕上的按钮更改DependencyProperty的值进行了测试)
显然,我在这里遇到了一个加载顺序问题,在文本属性绑定到视图模型之前设置了DependencyProperty的值。我的问题是,是否有一些事件可以钩住以识别文本属性的绑定何时完成?最好不修改文本框的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);
}
}
试着听听LayoutUpdated事件。我想它被称为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中的某些内容发生了更改。删除侦听器非常重要。