【问题标题】:Setting attached property in App.xaml在 App.xaml 中设置附加属性
【发布时间】:2014-01-08 11:32:03
【问题描述】:

我有以下 app.xaml:

<BaseApp x:Class ="MyApp"
         xmlns ="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x ="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:local ="clr-namespace:MyApp"
        Props.MyCustom="test"
         Startup ="Application_Startup"                                 
         >

<Application.Resources >
    < ResourceDictionary>
        ...
    </ ResourceDictionary>        

</Application.Resources>   

然后我需要能够从基础应用程序中读取属性:

 public partial class BaseApp : Application
{        

      static void MyFunc()
      {
           // Access property from here
           var myvar = Props.MyCustom
      }
}

我目前正在努力相信这需要在一个单独的类中,如下所示:

 public class Props : DependencyObject
{
    public string MyCustom
    {
        get { return ( string)GetValue(MyCustomProperty); }
        set { SetValue(MyCustomPropertyKey, value); }
    }

    public static readonly DependencyPropertyKey MyCustomPropertyKey =
        DependencyProperty.RegisterAttachedReadOnly("MyCustom" , typeof (string ), typeof (Props), new UIPropertyMetadata (0));           

    public static readonly DependencyProperty MyCustomProperty = MyCustomPropertyKey.DependencyProperty;

}

我是否以正确的方式处理这个问题,如果是,我需要做什么才能从 app.xaml 访问它?

编辑:

对于未来的旅行者,我最终解决这个问题的方式是在基类中简单地声明一个抽象的只读属性,并在后面的代码中覆盖它。不像我希望的那样整洁,但它确实有效。

【问题讨论】:

    标签: c# wpf xaml dependency-properties attached-properties


    【解决方案1】:

    附加属性应该有静态 getter 和 setter 方法,在你的情况下:

    public static string GetMyCustom(DependencyObject obj)
    {
        return (string)obj.GetValue(MyCustomProperty);
    }
    
    public static void SetMyCustom(DependencyObject obj, string value)
    {
        obj.SetValue(MyCustomProperty, value);
    }
    

    话虽如此,您仍然需要有一个DependencyObject 派生类的实例来设置属性,而System.Windows.Application 不是。换句话说,您不能在 MyApp 对象上设置附加属性。


    您可以不使用附加属性,而是将一个普通的 CLR 属性添加到您的 BaseApp 类:

    public class BaseApp : Application
    {
        public string MyCustom { get; set; }
    }
    

    并像这样使用它:

    <local:BaseApp x:Class="MyNamespace.MyApp" ...
                   MyCustom="Hello">
        <Application.Resources>
    
        </Application.Resources>
    </local:BaseApp>
    

    【讨论】:

    • 您是说附加属性无法做到这一点,还是根本不可能做到这一点?
    • 没错。附加属性是依赖属性,因此只能在派生自 DependencyObject 的类实例上设置。
    • 这让我回到最初的问题“我是否以正确的方式处理这个问题?”有没有其他方法可以达到同样的目的?
    • 不知道,因为您没有告诉我们为什么要在应用程序实例上设置属性。你想达到什么目的?
    • 公平点。我已经编辑了我的帖子,但实际上,我正在尝试设置一个将执行一些常见功能的基本应用程序,但它需要在运行时来自子应用程序的一条信息(因此是自定义属性)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-23
    • 2011-01-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多