Caliburn Micro,Wpf绑定嵌套模型

时间:2018-07-06 20:28:00

标签: c# .net mongodb mvvm caliburn.micro

嗨,我有一个带有Caliburn Micro和MongoDb的Wpf应用程序 我有这样的收藏

[Bson IgnoreExtraElements]
public class ResourceCollection : CompanyModel
{
    public ResourceCollection(string Vat) : base(Vat)
    {
    }

    private long _ResourceID;

    public long ResourceID
    {
        get { return _ResourceID; }
        set { _ResourceID = value; }
    }

    private string _Description;

    public string Description
    {
        get { return _Description; }
        set
        {
            _Description = value;
            NotifyOfPropertyChange(() => Description);
        }
    }
}

其中CompanyModel继承自PropertyChangedBase,并且我有一个视图模型:

public class ResourceCreateViewModel : Screen
{
    private IWindowManager _windowManager;
    private readonly AppConnection _appConnection;
    private readonly ResourceRepository _resourceRepository;

    private ResourceCollection _Resource;
    public ResourceCollection Resource
    {
        get
        {
            return _Resource;
        }
        set
        {
            _Resource = value;
            NotifyOfPropertyChange(() => Resource);
            NotifyOfPropertyChange(() => CanSave);
        }
    }
}

这是我的xaml

  <TextBox Text="{Binding Resource.Description, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Height="20" DockPanel.Dock="Right"></TextBox>

我的问题是,当我更改texbox中的值时,我的viewmodel类的集合未触发,如何将我的类绑定到文本框?

提前谢谢

1 个答案:

答案 0 :(得分:0)

不触发的原因很简单:未设置Resource对象,您仅在其上设置了一个属性。为了解决这个问题,您可以创建一个新的属性ResourceDescription并绑定到该属性:

    public string ResourceDescription
    {
    get
    {
        return _Resource.Description;
    }
            set
            {
                _Resource.Description = value;
                NotifyOfPropertyChange(() => ResourceDescription);
                NotifyOfPropertyChange(() => Resource);
                NotifyOfPropertyChange(() => CanSave);
            }
    }

Xaml:

<TextBox Text="{Binding Resource.Description, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"

但这有其自身的问题,因为视图模型中的更改不再更新您的视图。相反,您可以订阅资源PropertyChanged事件:

private ResourceCollection _Resource;
public ResourceCollection Resource
{
    get
    {
        return _Resource;
    }
    set
    {
        if(_Resource != null)
        {
            _Resource.PropertyChanged -= ResourcePropertyChanged;
        }

        _Resource = value;

        if(_Resource != null)
        {
            _Resource.PropertyChanged += ResourcePropertyChanged;
        }

        NotifyOfPropertyChange(() => Resource);
        NotifyOfPropertyChange(() => CanSave);
    }
}

private void ResourcePropertyChanged(object sender, EventArgs e)
{
    //you might be able to do something better than just notify of changes here
    NotifyOfPropertyChange(() => Resource);
    NotifyOfPropertyChange(() => CanSave);
}

这可能会很快变得复杂,特别是如果您要订阅嵌套在对象图中更深的属性。