简体   繁体   English

依赖属性未获取或设置值

[英]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. 我在WPF中创建了一个用户控件,在后面的代码中我创建了一些依赖属性。

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: 我向我的用户控件添加了几个WPF控件,其中一个是进度条,所以我尝试做的是公开Value progressBar属性,如下所示:

     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: 在XAML中我写了这个:

<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) 注意: DataContext以前是定义的,它是正确的,因为这是唯一不起作用的绑定)

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

Have you tried Mode=TwoWay: 你试过Mode = TwoWay:

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

I have also used PropertyMetadata instead of FrameworkPropertyMetadata 我还使用了PropertyMetadata而不是FrameworkPropertyMetadata

Try changing the name of your dependency property to be PascalCased: 尝试将依赖项属性的名称更改为PascalCased:

ValueProperty

You might also want to look at BindsTwoWayByDefault to make sure changes to your DP are written to the source object. 您可能还需要查看BindsTwoWayByDefault以确保将对 DP的更改写入源对象。

Turns out that my problem was that I didnt implement the INotifyPropertyChanged interface, so, the changes I did were not showed. 事实证明我的问题是我没有实现INotifyPropertyChanged接口,因此,我所做的更改没有显示出来。 But since I am new at WPF using MVVM I didnt know that. 但是因为我是WPF的新手,所以我不知道。

But you just need to create an ObservableObject, then your viewModel class has to inherit from it. 但是您只需要创建一个ObservableObject,然后您的viewModel类必须继承它。

Here is an example to create the ObservableObject class and how to inherit from it. 下面是创建ObservableObject类以及如何从中继承的示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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