绑定到用户控件的依赖项属性 [英] Binding to a usercontrols dependencyproperties

查看:99
本文介绍了绑定到用户控件的依赖项属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为FormattedTextBox的WPF UserControl项目,该项目在同一解决方案中包含一个TextBox和一个WPF窗口项目.

I have a WPF UserControl project named FormattedTextBox that contains a TextBox and a WPF window project in the same solution.

我的用户控件有两个依赖项注册,如下所示:

My user control has two dependency properties registered like this:

public static readonly DependencyProperty NumberProperty =  
    DependencyProperty.Register("Number", 
        typeof(double), 
        typeof(FormattedTextBox), 
        new FrameworkPropertyMetadata());  

public static readonly DependencyProperty NumberFormatStringProperty =
    DependencyProperty.Register("NumberFormatString", 
        typeof(string), 
        typeof(FormattedTextBox),
        new FrameworkPropertyMetadata());  

我在主窗口中创建了我的usercontrol的实例.主窗口填充INotifyPropertyChanged,并具有一个名为MyNumber的属性.在主窗口的XAML中,我尝试像这样绑定到MyNumber:

I make an instance of my usercontrol in the main window. The main window inplements INotifyPropertyChanged and has a property named MyNumber. In the XAML of the main window I try to bind to MyNumber like this:

Number="{Binding Path=MyNumber,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"   

绑定不起作用-我从不进入用户控件中Number属性的get或set方法.有人可以帮忙吗?

The binding doesn't work - I never get into the get or set on the Number property in the user control. Can anybody help?

推荐答案

在XAML中(或通过绑定或动画等)设置依赖项属性时,WPF无需调用CLR包装器即可直接访问基础DependencyObject和DependencyProperty.请参见 XAML加载和依赖项属性, 自定义依赖项属性的含义.

When a dependency property is set in XAML (or by binding or animation etc.), WPF directly accesses the underlying DependencyObject and DependencyProperty without calling the CLR wrapper. See XAML Loading and Dependency Properties, Implications for Custom Dependency Properties.

为了获得有关Number属性更改的通知,您必须注册

In order to get notified about changes of the Number property, you have to register a PropertyChangedCallback:

public static readonly DependencyProperty NumberProperty =  
    DependencyProperty.Register("Number", 
        typeof(double), 
        typeof(FormattedTextBox), 
        new FrameworkPropertyMetadata(NumberPropertyChanged));

private static void NumberPropertyChanged(
    DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
    var textBox = obj as FormattedTextBox;
    ...
}

这篇关于绑定到用户控件的依赖项属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆