如何在ViewModel中使用代码添加到页面布局? [英] How can I add to my page layout with code in the ViewModel?

查看:147
本文介绍了如何在ViewModel中使用代码添加到页面布局?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的页面布局如下:

<StackLayout x:Name="detailsLayout" VerticalOptions="FillAndExpand">
</StackLayout>

当我创建ViewModel时,我传入了指向页面的指针.我想做的是这样:

When I create my ViewModel I pass in a pointer to the page. What I would like to do is this:

公共类CardsViewModel:BaseViewModel {

public class CardsViewModel : BaseViewModel {

    private readonly Cards cardsPage;

    public CardsViewModel(Cards cardsPage)
    {
        this.cardsPage = cardsPage;
    }

    async public Task CardBtn()
    {
        cardsPage.detailsLayout.Children.Clear();

但是由于其保护级别,我无法访问detailsLayout.

But I don't have access to the detailsLayout due to its protection level.

有人可以告诉我如何获得此权限吗?

Can someone tell me how I can get access to do this?

推荐答案

上面的示例是耦合和打破ViewModelView(Page)之间分隔的示例.如果您想从MVVM模式中受益-不要保留对UI层的引用,并且绝对不要尝试直接在ViewModel中操纵UI层.

The example above is an example of coupling and breaking the separation between the ViewModel and the View(Page). If you want to benefit from MVVM pattern - don't keep a reference to your UI layer and definitely don't try to manipulate the UI layer directly in the ViewModel.

您应该做什么取决于您的需求,但是我可以给您一些建议:

What you should do instead is depends on your needs, however I can give you few ideas:

  1. 将逻辑封装在自己的UI控件中,公开您可以从ViewModel绑定到的委托,命令或属性以触发特定事件.
  2. 保持UI层,页面本身的逻辑,并使用MessagingCenterViewModel与之通信.
  1. Encapsulate the logic within the UI control it self, exposing a delegate, command or property you could bind to from your ViewModel to trigger the specific event.
  2. Keep the logic on UI layer, the Page itself and use a MessagingCenter to communicate to it from the ViewModel.

祝你好运.

PS:您可以在

P.S.: You can find more information and examples about MessagingCenter in the official Xamarin documentation. Just don't forget to unsubscribe, otherwise you will find yourself in a bad place.

这篇关于如何在ViewModel中使用代码添加到页面布局?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆