xamarin - 如何为 Xamarin Forms 模板制作 ViewModel?
问题描述
我有继承自 ContentView 的 Template1。出于这个问题的目的,我删除了模板中的很多内容以使其简单。
<?xml version="1.0" encoding="UTF-8"?>
<ContentView xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:local="clr-namespace:Japanese;assembly=Japanese" x:Class="Japanese.Template1" x:Name="this">
<Label Grid.Column="0" Text="{Binding Text, Source={x:Reference this}}" />
</ContentView>
和 Template1 C# 后端
namespace Japanese
{
public partial class Template1 : ContentView
{
public CardOrderTemplate()
{
InitializeComponent();
}
}
}
我希望这个模板在这个类中共享绑定,所以我尝试了一些不同的方法来做到这一点,但似乎没有一个有效。这就是我正在尝试的。不确定,但我想我需要模板的 ViewModel 之类的东西,但我不确定如何实现它。
namespace Japanese
{
public class SegBase : ContentView
{
public static readonly BindableProperty TextProperty = BindableProperty.Create(nameof(Text), typeof(string), typeof(SegTemplate), default(string));
public string Text
{
get { return (string)GetValue(TextProperty); }
set { SetValue(TextProperty, value); }
}
}
}
有谁知道我该怎么做?我尝试让 Template1 类从 SegBase 继承,但它给了我一个错误,因为 XAML 是 ContentView 类型,而 C# 不是从 ContentView 继承的。