卡利本微,WPF结合嵌套模型



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

[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 类集不会触发,如何将我的类绑定到文本框?

提前谢谢你

它不触发的原因很简单:资源对象没有被设置,你只设置了一个属性。要解决此问题,您可以创建一个新的属性 资源描述 并绑定到该属性:

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);
}

这可能会很快变得复杂,尤其是当您订阅嵌套在对象图中更深的属性时。

最新更新