我试图在 Xamarin.Forms 中通过 Entry 实现完美的 MVVM。
我的模型包含类型包括 string、int?、decimal?、bool? 等的属性。每当我绑定到字符串类型时,两种方式绑定都会起作用,因为文本属性具有字符串类型(它们匹配)。但是,一旦您尝试绑定回模型并且属性是 int 或 int?,它就不会更新模型的属性值。
在我的研究过程中,在 Xamarin 支持的帮助下,这是一个关于如何处理可为 null 类型的非常有用的线程:
XAML 代码:
<controls:NullableIntEntry Grid.Column="1" Grid.Row="14" NumericText="{Binding BusinessOwnership, Mode=TwoWay}" x:Name="lblBusinessOwnership"></controls:NullableIntEntry>Run Code Online (Sandbox Code Playgroud)
BindableEntry(条目扩展)代码:
using System;
using System.Collections;
using System.Collections.Specialized;
using System.Reflection;
using Xamarin.Forms;
namespace CreditBuilderApp.Controls
{
public class BindableEntry<T> : Entry
{
static bool firstLoad;
public static readonly BindableProperty NumericTextProperty =
BindableProperty.Create("NumericText", typeof(T), typeof(BindableEntry<T>),
null, BindingMode.TwoWay, propertyChanged: OnNumericTextChanged);
static void OnNumericTextChanged(BindableObject bindable, object oldValue, object newValue)
{
var boundEntry = (BindableEntry<T>)bindable;
if (firstLoad && …Run Code Online (Sandbox Code Playgroud)