我有 2 个"文本框",都绑定到带有"mode =2way"的源字符串属性。当我更改一个文本时,另一个完美地更改.但是当我以编程方式更改源字符串时,两者都不会更新。我不知道我错过了什么。这是我的代码片段:
Xaml 代码:
<StackPanel Orientation="Vertical">
<StackPanel.DataContext>
<local:x/>
</StackPanel.DataContext>
<TextBox Text="{Binding Text,Mode=TwoWay}" />
<TextBox Text="{Binding Text, Mode=TwoWay}"/>
</StackPanel>
<Button Content="Reset" Click="Button_Click"/>
按钮单击处理程序:
private void Button_Click(object sender, RoutedEventArgs e)
{
obj = new x() { Text="reset success"};
}
对象类:
class x:INotifyPropertyChanged
{
private string text;
public string Text
{
get { return text; }
set
{
text = value;
OnPropertyChange("Text");
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChange(string propertyName)
{
PropertyChangedEventHandler propertyChangedEvent = PropertyChanged;
if (propertyChangedEvent != null)
{
propertyChangedEvent(this, new PropertyChangedEventArgs(propertyName));
}
}
}
你创建了一个新对象。这就是原因。不要使新对象只是强制转换并更改实际绑定对象的内容(文本)。
创建新对象时,解决方案中的"订阅"将丢失。 :(
<StackPanel x:Name="myStackPanel" Orientation="Vertical">
<StackPanel.DataContext>
<local:x/>
</StackPanel.DataContext>
<TextBox Text="{Binding Text, Mode=TwoWay}" />
<TextBox Text="{Binding Text, Mode=TwoWay}"/>
</StackPanel>
上面的 XAML 摘录意味着:将堆栈面板的DataContext
设置为类 x
的新实例。由于实例化由 XAML 完成,因此在从堆栈面板的 DataContext
获取该实例之前,您没有对该x
实例的引用。
如果要测试数据绑定是否有效,则应修改类 x
的现有实例(当前设置为 DataContext
)。
private void Button_Click(object sender, RoutedEventArgs e)
{
var currentDataContext = (x)myStackPanel.DataContext;
x.Text = "reset success";
}
如果要按照注释中所述从代码中设置StackPanel
的DataContext
,则可以保存以删除 XAML 中的DataContext
设置部分。