c# - 如何在 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 永远不应该被更改,它总是将两个对象显示为相同的通过数据绑定。
我在这里遗漏了一些明显的东西还是应该采取不同的方法?
解决方案
原来,我需要做的是在 Object 上实现 ICloneable 接口,然后简单地克隆该对象。
我在我的 Object 类中添加了以下内容:
public class Object : ICloneable
{
public object Clone()
{
return MemberWiseClone();
}
}
然后我对我的页面构造函数进行了以下更改:
public PageUpdate(Object source) {
InitializeComponent();
Current = source;
Start = (Object)source.Clone();
}
我希望这可以帮助其他遇到此问题的人。
感谢 Steeeve 的解决方案。
推荐阅读
- android - androidTest:如何在 res/raw 目录中获取文件的路径?
- java - @EnableScheduling 似乎不适用于 Java 1.7 代码
- arrays - 在 Swift 4 中使用数组解析嵌套的 JSON 语句
- python - 如何正确拆分多个下划线?
- java - 改造 2 @FormUrlEncoded 与空字段
- wpf - 您可以将 ItemsControl 中的 ItemsPanel 绑定到 Items 集合的超集吗?
- java - 从 ts 前端发送到 java 后端的对象转换为 LinkedHashMap
- python - 如何通过 Google App Engine 中的应用程序将文件写入 Google Cloud Storage?
- c# - 在扩展类型中访问扩展方法?
- javascript - 如何在html css中使用页脚