C# 源程序更改时绑定目标控件未更新

C# 源程序更改时绑定目标控件未更新,c#,.net,xaml,data-binding,windows-store-apps,C#,.net,Xaml,Data Binding,Windows Store Apps,我有两个“文本框”,都绑定到一个带有“mode=2way”的源字符串属性。当我改变其中一个的文本时,另一个就完全改变了。但当我以编程方式更改源字符串时,两者都不会更新。我不知道我错过了什么。以下是我的代码片段: Xaml代码: <StackPanel Orientation="Vertical"> <StackPanel.DataContext> <local:x/> </StackPanel.DataContext>

我有两个“文本框”,都绑定到一个带有“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"/>
对象类:

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
DataContext
,则可以保存以删除XAML中的
DataContext
设置部分。

您创建了一个新对象。这就是原因。不要创建新对象,只需强制转换并更改实际绑定对象的内容(文本)


创建新对象时,“子描述”将丢失在解决方案中:(

我通过在代码中设置stackpanel的datacontext找到了一个解决方法。请检查答案或向我们添加更多帮助。我仍然不理解这种行为。我确信绑定可以工作,因为我在第一个文本框中键入的内容在第二个文本框中显示,但当我使用按钮重置两者时,不会发生任何情况……是的,绑定可以工作,两个文本框都可以绑定到相同的
x
实例。但单击按钮,您将重置
x
类的新实例,而不是那些文本框已绑定到的实例。
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>
private void Button_Click(object sender, RoutedEventArgs e) 
{ 
    var currentDataContext = (x)myStackPanel.DataContext;
    x.Text = "reset success";
}