将 TextField 绑定到 Xamarin.Forms 中的 Int 属性



我的 XAML 中有一个步进器和一个数字条目:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:views="clr-namespace:brahms.View"
x:Class="brahms.LabelRequestPage"
xmlns:ios="clr-namespace:Xamarin.Forms.PlatformConfiguration.iOSSpecific;assembly=Xamarin.Forms.Core"
Title="Request Labels"
ios:Page.UseSafeArea="True">
<ContentPage.Resources>
<ResourceDictionary>
<views:IntConverter x:Key="IntToString"/>
</ResourceDictionary>
</ContentPage.Resources>
<ContentPage.Content>
<StackLayout>
<StackLayout Orientation="Horizontal">
<Label Text="Number of labels:"/>
<Entry Text="{Binding Path=LabelQuantity, Mode=TwoWay, Converter={StaticResource IntToString}}" Keyboard="Numeric"/>
<Stepper Value="{Binding LabelQuantity}" />
</StackLayout>
<Button Text="Cancel" Clicked="CancelButton_Clicked"/>
</StackLayout>
</ContentPage.Content>
</ContentPage>

代码隐藏调用中的关联属性OnPropertyChanged

namespace brahms
{
public partial class LabelRequestPage : ContentPage
{
private int _quantity;
private int LabelQuantity
{
get
{
return _quantity;
}
set
{
_quantity = value;
OnPropertyChanged("LabelQuantity");
}
}
public LabelRequestPage()
{
LabelQuantity = 1;
InitializeComponent();
}
void CancelButton_Clicked(System.Object sender, System.EventArgs e)
{
Navigation.PopModalAsync();
}
}
}

但是,当我运行我的应用程序时,条目的默认状态为空,而不是值 1。步进器不会更改条目,并且在条目中设置值不会更改步进器的位置(如果您计算 + 和 - 的点击次数以计算其当前值(。

我的结论是,这两个控件没有绑定到代码隐藏中的属性,所以我的问题是为什么不呢?我需要执行哪些操作才能将这些控件绑定到该属性?

你可以这样做

<StackLayout Orientation="Horizontal" VerticalOptions="CenterAndExpand">
<Label Text="Number of labels:"/>
<Entry VerticalOptions="Start" HorizontalOptions="FillAndExpand" Text="{Binding LabelQuantity, Mode=TwoWay, Converter={StaticResource IntToString}}" Keyboard="Numeric"/>
<Stepper Value="{Binding LabelQuantity,Mode=TwoWay}" />
</StackLayout>

隐藏的代码应该是这样的。

public partial class LabelRequestPage : ContentPage
{
public LabelRequestPage()
{
InitializeComponent();
BindingContext = this;
LabelQuantity = 1;
}
private int _quantity;
public int LabelQuantity
{
get
{
return _quantity;
}
set
{
_quantity = value;
OnPropertyChanged(nameof(LabelQuantity));
}
}
}

对于转换器,您可以使用它。

public class IntConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is int)
return ((int)value).ToString();
else
return 0;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
int number = 0;
int.TryParse(value.ToString(), out number);
return number;
}
}