app.xaml.cs中的依赖属性

Vij*_*jay 7 wpf dependency-properties

我是WPF的新手,下面的问题可能对很多人来说很傻,请原谅我.

如何在app.xaml.cs中创建依赖项属性?

实际上,我试图创造它.以下代码,

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

    public string Temp
    {
        get { return (string)GetValue(TempProperty); }
        set { SetValue(TempProperty, value); }
    }
Run Code Online (Sandbox Code Playgroud)

抛出以下编译时错误:

当前上下文中不存在名称"GetValue"

当前上下文中不存在名称"SetValue"

有人可以帮助我吗?

谢谢!

Abe*_*cht 13

DependencyProperties只能在DependencyObjects上创建,并且由于Application(您的App类从其继承)不实现它,因此您无法直接在App类上创建DependencyProperty.

我假设您希望此属性支持绑定.如果是这种情况,您有两种选择:

  1. 在App.xaml.cs中实现INotifyPropertyChanged
  2. 使用您的属性创建一个DependencyObject派生类,并将其作为App的标准只读属性公开.然后可以通过"点击"将属性成功绑定到它们.即如果您的新属性名为Properties,您可以这样绑定:
   <TextBlock Text="{Binding Properties.Temp}" />
Run Code Online (Sandbox Code Playgroud)

如果属性需要成为绑定的目标,那么选项#2是您最好的选择.