你可以延长
ContentPage
创建一个通用类型(支持视图模型的类型参数),该类型反过来可用于
Binding
标记扩展。
虽然它可能不会给你像智能感知一样的支持-但绝对应该删除你的警告。
例如:
/// <summary>
/// Create a base page with generic support
/// </summary>
public class ContentPage<T> : ContentPage
{
/// <summary>
/// This property basically type-casts the BindingContext to expected view-model type
/// </summary>
/// <value>The view model.</value>
public T ViewModel { get { return (BindingContext != null) ? (T)BindingContext : default(T); } }
/// <summary>
/// Ensure ViewModel property change is raised when BindingContext changes
/// </summary>
protected override void OnBindingContextChanged()
{
base.OnBindingContextChanged();
OnPropertyChanged(nameof(ViewModel));
}
}
样品使用
<?xml version="1.0" encoding="utf-8"?>
<l:ContentPage
...
xmlns:l="clr-namespace:SampleApp"
x:TypeArguments="l:ThisPageViewModel"
x:Name="This"
x:Class="SampleApp.SampleAppPage">
...
<Label Text="{Binding ViewModel.PropA, Source={x:Reference This}}" />
...
</l:ContentPage>
代码隐藏
public partial class SampleAppPage : ContentPage<ThisPageViewModel>
{
public SampleAppPage()
{
InitializeComponent();
BindingContext = new ThisPageViewModel();
}
}
视图模型
/// <summary>
/// Just a sample viewmodel with properties
/// </summary>
public class ThisPageViewModel
{
public string PropA { get; } = "PropA";
public string PropB { get; } = "PropB";
public string PropC { get; } = "PropC";
public string[] Items { get; } = new[] { "1", "2", "3" };
}