绑定上的 WPF 刷新模型

发布于 2024-08-08 20:10:34 字数 279 浏览 3 评论 0原文

我想知道当 WPF 绑定到对象时是否有一种方法可以调用方法或更新 ViewModel 对象上的属性?

我想要这样做的原因是,当我的 viewModel 对象创建时,它们的数据模型仅包含一个 ID,用于在必要时从数据库查询数据。因此,当用户导航到该对象时,我希望视图通知 ViewModel 对象它正在被监视,从而告诉数据模型从数据库更新其值并将我的 ViewModel 对象置于加载状态(

如果 ViewModel 对象知道)当它们显示在屏幕上时进行自我更新,我可以避免手动刷新所有对象。

谢谢!

I was wondering if there was a way of calling a method or updating a property on my ViewModel object when WPF binds to the object ?

The reason I want to do this is that when my viewModel objects get created their data model only contains an ID that is used to query data from the database when necessary. So when the user navigates to that object I want the view to notify the ViewModel object that its being watched and as a result tell the data model to update its values from the DB and put my ViewModel object into a loading state

If the ViewModel objects knew to update them selves when they were displayed on screen I could avoid having to manually refresh all the objects.

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

携君以终年 2024-08-15 20:10:35

您可以将 Selected 属性添加到 ViewModel 中,该属性在对象被选中时设置。当 Selected 变为 true 时,您就可以访问数据库了。

You could add a Selected property to your ViewModel that gets set when the object becomes selected. When Selected turns to true, you could hit up your database.

﹎☆浅夏丿初晴 2024-08-15 20:10:34

当 WPF 绑定到 ViewModel 中的对象时,它将使用属性 getter 来获取值。

听起来您正在尝试使用惰性求值 - 只需让 getter 惰性实例化数据库中的信息即可:

private int entityId; // Set in advance
private Entity entityToFetch; // Will be fetched lazily

public Entity EntityToFetch
{
    get 
    {
        if (this.entityToFetch == null) // || this.entityToFetch.Id != this.entityId) - add this if you're letting this change at runtime...
        {
            this.entityToFetch = DataAccessLayer.FetchEntityForId(this.entityId);
        }

        return this.entityToFetch;
    }
}

When WPF binds to the object in your ViewModel, it's going to use the properties getter to fetch the value.

It sounds like you're trying to use lazy evaluation - just make the getter lazily instantiate the information from the DB:

private int entityId; // Set in advance
private Entity entityToFetch; // Will be fetched lazily

public Entity EntityToFetch
{
    get 
    {
        if (this.entityToFetch == null) // || this.entityToFetch.Id != this.entityId) - add this if you're letting this change at runtime...
        {
            this.entityToFetch = DataAccessLayer.FetchEntityForId(this.entityId);
        }

        return this.entityToFetch;
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文