How to define reference to existing object in XAML?
I 开发者_开发问答want to shorten settings bindings
{Binding Source={x:Static properties:Settings.Default}, Path=Password}
To something like
{settingsBinding Password}
By moving part of declaration to global resource dictionary. But it seems that I can't declare bindings here. Any ideas how to pull this off?
I want at least make it like this
{Binding Source={StaticResource Settings}, Path=Password}
So I don't have to include properties namespace every time.
To get the first syntax, you have to derive from Binding
and specify the source:
public class SettingsBinding : Binding {
public SettingsBinding(string path) : base(path) { Source = Settings.Default; }
public SettingsBinding() { Source = Settings.Default; }
}
You can then use: {xxx:SettingsBinding Password}
. However, you'll still have to specify the namespace of this class. I won't recommend this approach though: bindings tend to be quite verbose but you know what is happening since the syntax is always the same.
To get the second syntax you desire, simply define your x:Static
as a resource, eg:
<Window.Resources>
<x:Static Member="properties:Settings.Default" x:Key="Settings" />
</Window.Resources>
You can now reference it using StaticResource
.
First let me say I'm a relative WPF newbie and I have no idea what your level of expertise is so please forgive me if this isn't what you want. I can't quite tell if you want to solve a specific problem or want to know more generically how to use a resource to store a source path. I can only attempt an answer at the former.
If the data context of your enclosing object is set to Properties.Settings.Default then you could just use
{Binding Password}
which isn't exactly what you asked but still is pretty short. I can see how you might want to get to the password field no matter where you are and no matter what the current data context is. In my code all my XAML has a ViewModel data context. All view models derive from ViewModelBase. In ViewModelBase you could add a Password property and still use the syntax shown above.
精彩评论