![](/img/trans.png)
[英]How do I bind an object that is periodically modified to a treeview in C# WPF using the CommunityToolkit.MVVM?
[英]How do I data bind to a single instance of an object in 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;
設置數據上下文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();
}
我希望這可以幫助其他遇到此問題的人。
感謝斯蒂夫的解決方案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.