首页 > 解决方案 > ContentView 作为具有自己 ViewModel 的控件

问题描述

一直在为此苦苦挣扎,我有一个从 ContentView 继承的控件,它有自己的 ViewModel 来管理各种参数,从父页面我只需要传递一个属性,但是我不能让它传递到ViewModel,如果我不使用视图模型,我使用下面的,它工作正常

父页面

 <controls:CountdownTimerControl EndDate="{ Binding BidEndDate}">

控制

public static readonly BindableProperty EndDateProperty =
    BindableProperty.Create(nameof(EndDate), typeof(DateTime), typeof(CountdownTimerControl), default(DateTime), BindingMode.TwoWay,
       propertyChanged: (bindable, oldVal, newVal) => ((CountdownTimerControl)bindable).OnIsShown((DateTime)newVal));

    public DateTime EndDate
    {
        get => (DateTime)GetValue(EndDateProperty);
        set => SetValue(EndDateProperty, value);
    }

但是,如果我将控件更改为使用视图模型,则上述属性不会通过 BindableProperty

<controls:CountdownTimerControl EndDate="{ Binding BidEndDate}">
                                                <controls:CountdownTimerControl.BindingContext>
                                                    <viewModels:CountdownViewModel></viewModels:CountdownViewModel>
                                                </controls:CountdownTimerControl.BindingContext>
                                            </controls:CountdownTimerControl>

然后它根本不通过属性

苦苦挣扎,希望有任何帮助

干杯

标签: xamarinmvvmxamarin.forms

解决方案


而不是 EndDate = "{Binding BidEndDate}",

写 EndDate="{Binding Source={x:Reference dem}, Path=BindingContext.BidEndDate}"

其中“dem”是主页的名称。

 <?xml version="1.0" encoding="utf-8" ?>
 <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         xmlns:Markup="clr-namespace:Demo.Helper.MarkupExtensions"
         xmlns:viewModels="clr-namespace:Demo.ViewModels"
         xmlns:controls="clr-namespace:Demo.Views.UserControls"
         x:Name="dem"
         x:Class="Demo.Views.Dem">

<ContentPage.BindingContext>
    <viewModels:DemVM />
</ContentPage.BindingContext>

    <controls:CountdownTimerControl EndDate="{Binding Source={x:Reference dem}, Path=BindingContext.BidEndDate}">
        <controls:CountdownTimerControl.BindingContext>
            <viewModels:CountdownViewModel/>
        </controls:CountdownTimerControl.BindingContext>
    </controls:CountdownTimerControl>

</ContentPage>

推荐阅读