app.xaml.cs中的依赖项属性 [英] Dependency property in app.xaml.cs
问题描述
我是WPF的新手,对于许多人来说,以下问题可能看起来很愚蠢,请原谅。
I am new to WPF and the below question may look silly for many, please pardon me.
如何在app.xaml.cs中创建依赖项属性?
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); }
}
引发以下编译时错误:
名称'GetValue'在当前上下文中不存在
The name 'GetValue' does not exist in the current context
名称'SetValue'在当前上下文中不存在
The name 'SetValue' does not exist in the current context
有人可以帮我吗?
谢谢!
推荐答案
DependencyProperties只能在DependencyObjects上创建,并且由于Application(您的App类继承自该应用程序)没有实现它,因此您不能直接在App类上创建DependencyProperty。
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:
- 在App.xaml.cs中实现INotifyPropertyChanged
- 创建一个具有您的属性的DependencyObject派生类,并将其公开为您的App的标准只读属性。然后可以通过点入属性来成功绑定属性。
,即如果您的新属性称为Properties,则可以这样绑定:
<TextBlock Text="{Binding Properties.Temp}" />
如果属性需要成为Binding的目标,那么选项#2是最好的选择。
If the property needs to be the target of a Binding, then option #2 is your best bet.
这篇关于app.xaml.cs中的依赖项属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!