Thursday, 22 August 2013

Binding to a property within a static class instance

Binding to a property within a static class instance

What I am trying to achieve
I have a WPF application (it's just for testing) and I want to bind the
text (Content) of a label to a property somewhere. The idea is that this
property value will be changed when the user chooses a different language.
When the property changes, I want the label text to update with the new
value.
What I have tried
I tried to create a static class with a static property for the label
value. For example:
public static class Language
{
public static string Name = "Name";
}
I then was able to bind this value to my label using XAML like so:
Content="{Binding Source={x:Static lang:Language.Name}}"
And this worked fine for showing the initial value of "Name". The problem
is, when the Name property changes the label value doesn't change.
So, back to the drawing board (Google). Then I found this answer which
sounded exactly like what I needed. So here was my new attempt at this:
public class Language
{
public static Language Instance { get; private set; }
static Language() { Instance = new Language(); }
private Language() { }
public string Name = "Name";
}
With my binding changed it this:
Content="{Binding Source={x:Static lang:Language.Instance}, Path=Name}"
The problem I have now though is that despite not having any compile
errors/warnings, the label is just blank, there appears to be no content
at all.
Questions
What am I missing with my latest attempt? Why is the label blank? Am I
going in completely the wrong direction trying to solve this problem?

No comments:

Post a Comment