【发布时间】: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