0
votes

If I have a class

class ContentList 
{
    public string Content1 { get; set; }
    public string Content2 { get; set; }
}

and a textbox in my XAML file with a binding

<TextBox Text="{Binding Content1, Mode=TwoWay}" ... />

I set the DataContext in my .cs file by

protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
{
    this.DataContext = new ContentList();
}

How do I change the binding to Content2?

Also, how do I access and change Content1 in code? this.DataContext.Content1 = "string" does not work.

2

2 Answers

2
votes

To change the binding of your TextBox from Content1 to Content2, first give the TextBox a name, and then in the code-behind you can do this:

myTextBox.SetBinding(TextBox.TextProperty, new Binding("Content2"));

To access Content1 in the code, you can do this:

string content = ((ContentList)this.DataContext).Content1;
1
votes

You change the Binding to Content2 by writing Content2 in the XAML file. You cannot do this dynamically. Well, that's not quite right. It's possible to use the Binding class to establish a new binding in code. But you shouldn't do that in this case because it defeats declarative programming in XAML.

Content1 may be accessed like this: ((ContentList)DataContext).Content1

However, this is not the best practice. Try to learn about MVVM.