【问题标题】:bound target control not updating when source changed programatically当源以编程方式更改时,绑定目标控件不更新
【发布时间】:2014-02-28 05:30:34
【问题描述】:

我有 2 个“文本框”都绑定到具有“mode =2way”的源字符串属性。当我将文本更改为一个时,另一个会完美更改。但是当我以编程方式更改源字符串时,都不会更新。我无法弄清楚我错过了什么。这是我的代码 sn-ps:

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的datacontext找到了一种解决方法
  • 请检查答案或向我们添加更多帮助

标签: c# .net xaml data-binding windows-store-apps


【解决方案1】:

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

当您创建一个新对象时,“订阅”会在您的解决方案中丢失。 :(

【讨论】:

    【解决方案2】:
    <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 摘录意味着:将 stackpanel 的 DataContext 设置为 x 类的新实例。因为实例化是由 XAML 完成的,所以在从 stackpanel 的 DataContext 获取之前,您没有对该 x 实例的引用。

    如果你想测试你的数据绑定是否有效,你应该修改类x的现有实例(当前设置为DataContext)。

    private void Button_Click(object sender, RoutedEventArgs e) 
    { 
        var currentDataContext = (x)myStackPanel.DataContext;
        x.Text = "reset success";
    }
    

    如果您想按照注释中的说明从代码中设置StackPanelDataContext,只需删除XAML 中的DataContext 设置部分即可。

    【讨论】:

    • 我还是不明白这种行为。我确信绑定可以正常工作,因为我在第一个文本框中键入的任何内容都会显示在第二个文本框中,但是当我使用按钮重置两者时,什么都没有发生......
    • 是的,绑定有效,两个文本框都绑定到同一个 x 实例。但是在单击按钮时,您正在重置 x 类的新实例,而不是那些文本框已经绑定到的实例。
    猜你喜欢
    • 1970-01-01
    • 2013-02-03
    • 1970-01-01
    • 1970-01-01
    • 2017-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-10
    相关资源
    最近更新 更多