Binding to a usercontrols dependencyproperties

陌路散爱 提交于 2019-12-02 16:29:24

问题


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());  

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}"   

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


回答1:


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.

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;
    ...
}


来源:https://stackoverflow.com/questions/14216714/binding-to-a-usercontrols-dependencyproperties

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!