Question

I have the following 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>   

I then need to be able to read the property from the base application:

 public partial class BaseApp : Application
{        

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

I'm currently working on the belief that this needs to be in a separate class, as follows:

 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;

}

Am I approaching this in the right way, and if so, what do I need to do to be able to access this from app.xaml?

EDIT:

For future travellers, the way I finally managed this was to simply declare an abstract read-only property in the base class and override it in code behind. Not as neat as I would have liked, but it works.

Was it helpful?

Solution

Attached properties should have static getter and setter methods, in your case:

public static string GetMyCustom(DependencyObject obj)
{
    return (string)obj.GetValue(MyCustomProperty);
}

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

Having said that you would still have to have an instance of a DependencyObject-derived class to set the property on, which System.Windows.Application is not. In other words, you can't set an attached property on your MyApp object.


Instead of using an attached property, you might just add a plain CLR property to your BaseApp class:

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

and use it like this:

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

    </Application.Resources>
</local:BaseApp>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top