app.xaml.cs 中的依赖属性

发布于 2024-08-02 19:24:56 字数 499 浏览 3 评论 0原文

我是 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); }
    }

抛出以下编译时错误:

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

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

有人可以帮助我吗?

谢谢你!

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!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

温折酒 2024-08-09 19:24:56

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

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

  1. 在 App.xaml.cs 中实现 INotifyPropertyChanged
  2. 创建一个包含您的属性的 DependencyObject 派生类,并将其公开为您的应用程序的标准只读属性。然后可以通过“点下”将这些属性成功绑定到它们。
    即,如果您的新属性称为 Properties,您可以像这样绑定:
   <TextBlock Text="{Binding Properties.Temp}" />

如果该属性需要成为 Binding 的目标,那么选项 #2 是您最好的选择。

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.

埋情葬爱 2024-08-09 19:24:56

包含依赖属性的类必须继承自 DependencyObject。

You class that contains dependency properties must inherit from DependencyObject.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文