C# 在App.xaml中设置附加属性
我有以下app.xaml:C# 在App.xaml中设置附加属性,c#,wpf,xaml,dependency-properties,attached-properties,C#,Wpf,Xaml,Dependency Properties,Attached Properties,我有以下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
<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 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访问此问题
编辑:
对于未来的旅行者,我最终实现这一点的方法是在基类中声明一个抽象只读属性,并在代码隐藏中重写它。没有我希望的那么整洁,但它可以工作。附加属性应该有静态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
的类实例上设置。然后,我又回到了最初的问题“我是否以正确的方式处理此问题?”是否有其他方法实现相同的目标?不知道,因为您还没有告诉我们为什么要在应用程序实例上设置属性。你想达到什么目的?说得对。我已经编辑了我的文章,但实际上,我正在尝试设置一个基本应用程序,该应用程序将执行一些常见的功能,但它需要在运行时从子应用程序获得一条信息(因此需要自定义属性)
<local:BaseApp x:Class="MyNamespace.MyApp" ...
MyCustom="Hello">
<Application.Resources>
</Application.Resources>
</local:BaseApp>