首页 > 解决方案 > 如何在 C# WPF 中将数据绑定到对象的单个实例?

问题描述

我正在编写一个 WPF 页面来更新存储在 SQL 服务器上的数据,而我编写它的方式需要存储原始数据的副本以创建 WHERE 子句。
所以,我想要做的是将两个数据副本存储在页面上的变量中。一个保留为原始对象,一个用作数据绑定上下文,声明如下:

public Object Current { get; set; }
private readonly Object Start = new Object();

在我的构造函数中声明为:

public PageUpdate(Object source) {
    InitializeComponent();
    Current = source;
    Start = source;
}

如果我对数据绑定的理解是正确的,数据绑定应该是完全看不到Start对象的。我尝试了几种方法,包括使用 设置数据上下文DataContext = Current;,使用 XAML 以两种不同的方式描述它:

<TextBox x:Name="TextBox1" Text="{Binding Object.ObjectTextProperty, RelativeSource={RelativeSource FindAncestor AncestorType=Page}" />
<Page d:DataContext="{d:DesignInstance Type=Object}">
    <TextBox x:Name="TextBox1" Text="{Binding ObjectTextProperty}" />
</Page>

最后尝试在代码隐藏中设置每个绑定属性:

TextBox1.SetBinding(TextBox.TextProperty, new Binding("ObjectTextProperty")
    {
        BindingGroupName = "bindingGroup",
        Source = Current,
        Mode = BindingMode.TwoWay
    });

以及上述的各种组合。

每次我使用它时,我都会在从前端编辑数据后通过将 Start 和 Current 打印到调试控制台进行测试,即使据我所知,Start 永远不应该被更改,它总是将两个对象显示为相同的通过数据绑定。

我在这里遗漏了一些明显的东西还是应该采取不同的方法?

标签: c#wpfdata-binding

解决方案


原来,我需要做的是在 Object 上实现 ICloneable 接口,然后简单地克隆该对象。

我在我的 Object 类中添加了以下内容:

public class Object : ICloneable
{
    public object Clone()
    {
        return MemberWiseClone();
    }
}

然后我对我的页面构造函数进行了以下更改:

public PageUpdate(Object source) {
    InitializeComponent();
    Current = source;
    Start = (Object)source.Clone();
}

我希望这可以帮助其他遇到此问题的人。

感谢 Steeeve 的解决方案。


推荐阅读