xamarin - 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>
然后它根本不通过属性
苦苦挣扎,希望有任何帮助
干杯
解决方案
而不是 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>
推荐阅读
- ruby - each_with_object 的累加器不断重新初始化
- swift - MapKit SearchResultsUpdating 未调用
- javascript - 如何使用 00:00 时间格式修复我的 Javascript 秒表?(秒:毫秒)
- android - 如何在进入下一个活动之前使用信息验证几个 TextView 字段
- java - 如何在 java (endian) 中渲染 GL_SHORT?
- r - r中中缀运算符和复合赋值运算符之间的区别
- c++ - 什么时候使用hpp,什么时候使用h + cpp?
- objective-c - AVSpeechUtterance 包含空字符串?
- javascript - 用于返回 CSS 样式的 Webpack 加载器?
- wordpress - 我希望 get_posts 只返回登录用户的帖子