[英]Setting attached property in App.xaml
我有以下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中访问它?
编辑:
对于将来的旅行者,我最终设法做到这一点的方法是在基类中简单地声明一个抽象的只读属性,并在后面的代码中重写它。 不像我想要的那样整洁,但是可以。
在您的情况下,附加属性应具有静态的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对象上设置附加属性。
除了使用附加属性之外,您还可以在BaseApp
类中添加一个普通的CLR属性:
public class BaseApp : Application
{
public string MyCustom { get; set; }
}
并像这样使用它:
<local:BaseApp x:Class="MyNamespace.MyApp" ...
MyCustom="Hello">
<Application.Resources>
</Application.Resources>
</local:BaseApp>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.