简体   繁体   中英

Dependency Property does not get or set Value

I have created a user control in WPF, and in the code behind I have created some dependency properties.

I added several WPF controls to my user control, one of the is a progress bar, so What I tried to do is to expose the Value progressBar property as below:

     public static readonly DependencyProperty valueProperty = DependencyProperty.Register(
        "Value",
        typeof(Double),
        typeof(MyUserControl),
        new FrameworkPropertyMetadata(
            ValuePropertyCallback));

    private static void ValuePropertyCallback(DependencyObject controlInstance, DependencyPropertyChangedEventArgs args)
    {
        MyUserControl myUserControlInstance = (ProgressControl)controlInstance;
        myUserControlInstance.progressBar.Value = (Double)args.NewValue;
    }

    public Double Value
    {
        get { return (Double)GetValue(valueProperty); }
        set { SetValue(valueProperty, value); }
    }

And in XAML I have written this:

<MyUserControl Name="myControl" Value="{Binding ProgressBarValue}" >

But It seems not to be working, neither setting nor getting the value.

I have a couple hours reviewing this but I cant realize what I am doing wrong.

Hope you can help me, Thank you in advance.

( Note: DataContext are defined previously and it is correct since this is the only binding that does not work)

valueProperty <---->“Value”不匹配...(v / V):=)

Have you tried Mode=TwoWay:

<MyUserControl Name="myControl" Value="{Binding ProgressBarValue, Mode=TwoWay}" > 

I have also used PropertyMetadata instead of FrameworkPropertyMetadata

Try changing the name of your dependency property to be PascalCased:

ValueProperty

You might also want to look at BindsTwoWayByDefault to make sure changes to your DP are written to the source object.

Turns out that my problem was that I didnt implement the INotifyPropertyChanged interface, so, the changes I did were not showed. But since I am new at WPF using MVVM I didnt know that.

But you just need to create an ObservableObject, then your viewModel class has to inherit from it.

Here is an example to create the ObservableObject class and how to inherit from it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM