C# WPF中的大规模显式绑定更新

C# WPF中的大规模显式绑定更新,c#,wpf,data-binding,C#,Wpf,Data Binding,我正在编写一个WPF应用程序,其中包括一些模型。 每个模型都有一个编辑器控件,我可以使用该控件查看和编辑该模型的对象 例如: <Label Content="{Binding ID}" /> <TextBox Text="{Binding FirstName}" /> <TextBox Text="{Binding LastName}" /> <TextBox Text="{Binding

我正在编写一个WPF应用程序,其中包括一些模型。 每个模型都有一个编辑器控件,我可以使用该控件查看和编辑该模型的对象

例如:

        <Label Content="{Binding ID}" />

        <TextBox Text="{Binding FirstName}" />
        <TextBox Text="{Binding LastName}" />
        <TextBox Text="{Binding Department}" />
        <TextBox Text="{Binding TelephoneNumber}" />
        <xceed:ByteUpDown Value="{Binding AccessLevel1}" Maximum="64" />
        <xceed:ByteUpDown Value="{Binding AccessLevel2}" Maximum="64"/>
        <xceed:IntegerUpDown Value="{Binding PIN}" />
        <xceed:IntegerUpDown Value="{Binding KeyCode}" />
        <xceed:IntegerUpDown Value="{Binding UserLimit}" />

不更新
模型
(将值保留在
视图模型
级别)直到“保存”,并在“取消”时将值从
模型
重新加载到
视图模型

实现这一点的另一种方法是在虚拟机上保留和公开临时模型,并将UI与之绑定


用户单击“保存”后,使用临时模型值更新实际模型。如果用户单击“取消”,只需清除临时模型值。使用实际选定的模型值不断更新临时模型。因此,您的临时模型将充当值的中间容器。

围绕您的模型创建一个包装器对象,并用它绑定。按下Save键后,将所有值从包装器对象复制到模型中。是否介意详细说明?我应该在模型和视图之间创建另一个抽象层吗?是的,但是如果您想保持它
视图
/
模型
,您还可以在
模型
级别从原始模型加载/保存一个绑定到的模型的“副本”。但是拥有
Model
/
View
/
ViewModel
层(
MVVM
)并在
VM
上执行这种应用程序行为肯定是一个更好的选择。谢谢你,我将编写一个ViewModel并使用它。guess@franssu在他的评论中向你建议了这一点
class Key
{
    private KeyViewModel viewModel;

    public KeyViewModel ViewModel
    {
        get
        {
            if (viewModel == null)
                viewModel = new KeyViewModel(this);
            return viewModel;
        }
    }
    // -=-=- Lots & lots of properties -=-=- //
}

public class KeyViewModel : Key
{
    public Key Parent { get; set; }
    public KeyViewModel(Key parent)
    {
        Parent = parent;
        CopyFromModel();
    }
    public void CopyToModel()
    {
        Type t = typeof(Key);
        var props = t.GetProperties();
        foreach (var p in props)
        {                
            if (p.CanWrite)
                p.SetValue(Parent, p.GetValue(this));
        }
    }
    public void CopyFromModel()
    {
        Type t = typeof(Key);
        var props = t.GetProperties();
        foreach (var p in props)
        {
            if (p.CanWrite)
                p.SetValue(this, p.GetValue(Parent));
        }
    }
}