Dependency property in app.xaml.cs

会有一股神秘感。 提交于 2019-12-19 17:11:33

问题


I am new to WPF and the below question may look silly for many, please pardon me.

How can I create a dependency property in app.xaml.cs?

Actually, I tried to created it. The below code,

    public static DependencyProperty TempProperty =
       DependencyProperty.Register("Temp", typeof(string), typeof(App));

    public string Temp
    {
        get { return (string)GetValue(TempProperty); }
        set { SetValue(TempProperty, value); }
    }

throws the below compile time errors:

The name 'GetValue' does not exist in the current context

The name 'SetValue' does not exist in the current context

Can anybody help me in this?

Thank you!


回答1:


DependencyProperties can only be created on DependencyObjects, and since Application (which your App class inherits from) doesn't implement it, you can't create a DependencyProperty directly on the App class.

I assume you want this property to support binding. If this is the case, you have two options:

  1. Implement INotifyPropertyChanged in App.xaml.cs
  2. Create a DependencyObject derived class with your properties on it, and expose it as a standard read-only property of your App. The properties can then be successfully bound by "dotting-down" to them. i.e if your new property is called Properties, you can bind like so:
   <TextBlock Text="{Binding Properties.Temp}" />

If the property needs to be the target of a Binding, then option #2 is your best bet.




回答2:


You class that contains dependency properties must inherit from DependencyObject.



来源:https://stackoverflow.com/questions/1349034/dependency-property-in-app-xaml-cs

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