将属性从CustomControl更改为DataContext

时间:2019-03-19 16:27:33

标签: c# wpf mvvm

我正在为插件编写接口。我具有自定义的Control,一个MainViewModel和一个我保存并加载的Settings类。 在这些设置中,我有一个实体列表,基本上我只是想提供自定义控件,其余的(图标,可用实体等)完成。现在,这一切都可以在我的代码中正常运行,唯一的问题是,是否保存设置取决于我在MainViewModel中设置的标志(插件限制)。通过ObservableCollection,我注意到何时添加和删除实体,而不是何时更改实体的值。

我的基本截断版式:

public class MainViewModel : INotifyPropertyChanged
{
    //This Property gets serialized and deserialized
    public MySettings Settings { get;set; }
    //With Settings.PropertyChanged handling
    //I kinda want to keep this lightweight for abstraction/inheritance reasons.
}

[DataContract]
public class Entity
{
    //Other Data
    [DataMember]
    public bool IsInverted{ get;set; }
}

[DataContract]
public class MySettings : INotifyPropertyChanged
{
    private ObserverableList<EntityModel> entities;
    [DataMember]
    public ObserverableList<EntityModel> Entities 
    {
        get => entities;
        set
        {
            if (entities == value) return;
            entities = value;
            entities.CollectionChanged += (a,b) => OnPropertyChanges(nameof(Entities));
        }
    }
}

public partial class EntityListControl : UserControl, INotifyPropertyChanged
{
    //DependencyProperties

    //This property is bound to the MainViewModel.Settings.Entities
    public ObservableCollection<CameraModel> CameraList
    {
        get => (ObservableCollection<CameraModel>)GetValue(CameraListProperty);
        set => SetValue(CameraListProperty, value);
    }
    public ObservableCollection<CameraViewModel> CameraViewModels { get; set; }

    //Add/RemoveCommands connecting model list with viewmodel list.
}

public class EntityViewModel : INotifyPropertyChanged
{
    private Entity model;
    //Properties => model.Property
    //Other data like images and names not saved
}

再加上一个xaml控件,该控件具有一个列表,其中包含用于布尔值和其他内容的复选框。

要注意到Entity属性何时更改,最明显的解决方案是使用INotifyPropertyChanged增强Entity,但这基本上意味着我有两个相同模型的ViewModel(是否破坏了MVVM?)。 因此,我想知道是否有另一种方法可以执行此操作,而我不需要几秒钟的ViewModel,还是将EntityViewModel List(和周围的代码)封装到MainViewModel中而不将各种命令绑定到and的好方法从UserControl中(添加/删除)。

0 个答案:

没有答案
相关问题