简体   繁体   English

XAML更改绑定和DataContext元素

[英]XAML Changing Binding and DataContext Element

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 和我的XAML文件中的带有绑定的文本框

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

I set the DataContext in my .cs file by 我在.cs文件中设置了DataContext

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

How do I change the binding to Content2? 如何更改对Content2的绑定?

Also, how do I access and change Content1 in code? 另外,如何在代码中访问和更改Content1? this.DataContext.Content1 = "string" does not work. this.DataContext.Content1 =“字符串”不起作用。

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: 要将TextBox的绑定从Content1Content2 ,请首先为TextBox一个名称,然后在后面的代码中执行以下操作:

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

To access Content1 in the code, you can do this: 要访问Content1中的Content1 ,可以执行以下操作:

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

You change the Binding to Content2 by writing Content2 in the XAML file. 您可以通过在XAML文件中写入Content2来更改对Content2的绑定。 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. 可以使用Binding类在代码中建立新的绑定。 But you shouldn't do that in this case because it defeats declarative programming in XAML. 但是在这种情况下,您不应该这样做,因为它会使XAML中的声明式编程失败。

Content1 may be accessed like this: ((ContentList)DataContext).Content1 可以这样访问Content1((ContentList)DataContext).Content1

However, this is not the best practice. 但是,这不是最佳实践。 Try to learn about MVVM. 尝试了解MVVM。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM