[英]Bind Entry TextChanged to the CanExecute method of button command in Xamarin.Forms
[英]How to bind Xamarin.Forms Entry to a Non String Type such as Decimal
我創建了Entry,我試圖將它綁定到Decimal屬性,如下所示:
var downPayment = new Entry () {
HorizontalOptions = LayoutOptions.FillAndExpand,
Placeholder = "Down Payment",
Keyboard = Keyboard.Numeric
};
downPayment.SetBinding (Entry.TextProperty, "DownPayment");
當我嘗試在模擬器上輸入Entry時,我收到以下錯誤。
對象類型System.String無法轉換為目標類型:System.Decimal
在撰寫本文時,在綁定時沒有內置轉換(但這是有效的),因此綁定系統不知道如何將您的DownPayment
字段(小數)轉換為Entry.Text
(一個字符串) )。
如果OneWay
綁定符合您的預期,則字符串轉換器將完成此任務。 這適用於Label
:
downPayment.SetBinding (Entry.TextProperty, new Binding ("DownPayment", stringFormat: "{0}"));
對於Entry
,您希望綁定在兩個方向都有效,因此您需要一個轉換器:
public class DecimalConverter : IValueConverter
{
public object Convert (object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value is decimal)
return value.ToString ();
return value;
}
public object ConvertBack (object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
decimal dec;
if (decimal.TryParse (value as string, out dec))
return dec;
return value;
}
}
現在,您可以在綁定中使用該轉換器的實例:
downPayment.SetBinding (Entry.TextProperty, new Binding ("DownPayment", converter: new DecimalConverter()));
注意:
OP的代碼應該在1.2.1及更高版本中開箱即用(來自Stephane對問題的評論)。 對於低於1.2.1的版本,這是一種解決方法
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.