如何在ViewModel中使用代码添加到页面布局? [英] How can I add to my page layout with code in the 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?
推荐答案
上面的示例是耦合和打破ViewModel
和View(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:
- 将逻辑封装在自己的UI控件中,公开您可以从
ViewModel
绑定到的委托,命令或属性以触发特定事件. - 保持UI层,页面本身的逻辑,并使用
MessagingCenter
从ViewModel
与之通信.
- 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. - Keep the logic on UI layer, the Page itself and use a
MessagingCenter
to communicate to it from theViewModel
.
祝你好运.
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屋!