Bohrend
Bohrend

Reputation: 1497

Issue with databinding to class?

I'm having an issue with databinding a textblock to a custom prop inside another class, what am I doing wrong?

mainpage:

  public partial class MainPage : PhoneApplicationPage
{
    // Constructor
    public MainPage()
    {
        InitializeComponent();
        InitializeLanguage();

    }

    private void InitializeLanguage()
    {
        LanguageHelper lh = new LanguageHelper();

        // this.TitlePanel.DataContext = lh;
        txtTitle.DataContext = lh;
    }
}

databinding:

 <TextBlock x:Name="txtTitle" 
                   Text="{Binding homepage_subheading}" 
                   Style="{StaticResource PhoneTextNormalStyle}" 
                   Foreground="White"
                   Margin="12,0"/>

LanguageHelper class:

public class LanguageHelper
{
    public String homepage_subheading;

    public void changeLanguage()
    {
        if (true)
        {
            //english
            homepage_subheading = "This is the top / sub Heading";
            }
    }

}

Upvotes: 1

Views: 53

Answers (2)

King King
King King

Reputation: 63317

You should declare some dependency property or use INotifyPropertyChanged, I would like to use a dependency property:

public class LanguageHelper : DependencyObject {
  public static DependencyProperty Hompage_subheadingProperty =  
  DependencyProperty.Register("Homepage_subheading", typeof(string), typeof(LanguageHelper));
  public String Homepage_subheading {
     get { return (string) GetValue(Homepage_subheadingProperty);}
     set { SetValue(Homepage_subheadingProperty, value);}
  }
}

Note about the naming convention in C#, all properties should have first letter capitalized.

Upvotes: 0

nemesv
nemesv

Reputation: 139748

You don't have a property but a public field, and the databinding engine only works on properties.

So you need to change your class:

public String homepage_subheading { get; set; }

If you want to also notify the UI with your changes of your properties your LanguageHelper should implement the INotifyPropertyChanged interface and fire the PropertyChange event when you modify your properties.

Upvotes: 2

Related Questions