12

I have a Property in my App.xaml.cs called User that holds the User details. I have read here that you can't have a dependency property on the App class.

I chose to use App.cs because it is global to the entire program and this is used for access control, but any alternatives are welcome.

Now my question is how can I bind to this property from my UserControls and Windows.

IsEnabled="{Binding Path=User, Converter={StaticResource hasAccessConverter}, ConverterParameter=Mid}"

This obviously only works on a property on the DataContext. I want to access the property on the App. Can someone show me an example of the binding to the App.xaml.cs property if I implement INotifyChanged?

ΩmegaMan
  • 29,542
  • 12
  • 100
  • 122
Oliver
  • 35,233
  • 12
  • 66
  • 78

3 Answers3

35

I have read here that you can't have a dependency property on the App class.

Indeed you can't, because Application doesn't inherit from DependencyObject. However, it's not necessary : only the target property of a binding needs to be a dependency property.

If you want to bind to a property of your App class, you can do it like that :

IsEnabled="{Binding Path=User, Source={x:Static Application.Current}}"
Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758
  • 1
    Just a note that this in a no-can-do in Silverlight. x:Static and x:Type don't exist in the Silverlight world. – Oliver Feb 21 '11 at 15:29
  • 2
    Remember to implement INotifyPopertyChanged to see the changes to that property reflected on the user interface. – sergiol Aug 21 '12 at 17:28
  • In the above, you're binding a `bool` to a `User`, that doesn't make any sense. I assume you want to bind it to `User.IsEnabled` -- how would one do that? – Dmitri Nesteruk Jun 20 '13 at 08:18
  • @DmitriNesteruk, I agree, it doesn't seem to make much sense... I just took the code from the OP and changed it a little, but I forgot the converter along the way. Assuming there is a User.IsEnabled property, you could just use `Path=User.IsEnabled`; otherwise, you can use a converter just like in the OP's code. – Thomas Levesque Jun 20 '13 at 11:45
4

And to access it programatically in C# you can do this:

((App)Application.Current).YourMethod
((App)Application.Current).YourProperty
Gus Cavalcanti
  • 10,527
  • 23
  • 71
  • 104
-1

You can bind declaratively in Silverlight to Application.Current by using a custom converter.

See my blog post here

  • 2
    Lone link is [considered a poor answer](http://stackoverflow.com/faq#deletion) since it is meaningless by itself and target resource is not guaranteed to be alive in the future. [It would be preferable](http://meta.stackexchange.com/q/8259) to include the essential parts of the answer here, and provide the link for reference. – j0k Jan 02 '13 at 12:32