绑定到usercontrols dependencyproperties

时间:2013-01-08 14:08:53

标签: wpf mvvm dependency-properties

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

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

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,如下所示:

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

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

1 个答案:

答案 0 :(得分:1)

当在XAML中设置依赖项属性(或通过绑定或动画等)时,WPF直接访问底层的DependencyObject和DependencyProperty而不调用CLR包装器。见XAML Loading and Dependency Properties, 自定义依赖属性的含义。

要获得有关Number属性更改的通知,您必须注册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;
    ...
}