[英]Display label text in uppercase using xaml in Xamarin.Forms
我有一個用戶名標簽,需要將其視為大寫,但這應該只與 UI 相關。 數據(字符串)應該作為實際情況保存在數據庫中,無論它是什么。 誰能告訴我是否可以通過背后的代碼將其轉換為大寫?
您可以將Label.TextTransform
與TextTransform.Uppercase
Label.TextTransform
使用。
XAML
<Label TextTransform="Uppercase" />
C#
var label = new Label
{
TextTransform = TextTransform.Uppercase
};
如您所知,您可以從后面的代碼中執行此操作:
string data = "my data";
UILabel myLabel = new UILabel();
myLabel.Text = data.ToUpper();
因此請記住,您不想這樣做,您需要從 UILabel 派生並創建自己的,然后只需將 ToUpper() 添加到 get;set; 的末尾; Text 屬性的值。
using CoreGraphics;
using System;
using UIKit;
namespace MyApp.Controls
{
partial class Control_UpperLabel : UILabel
{
public Control_UpperLabel IntPtr handle) : base(handle)
{
//
}
public Control_UpperLabel()
{
//
}
public override void Draw(CGRect rect)
{
base.Draw(rect);
}
public override string Text { get => base.Text.ToUpper(); set => base.Text = value.ToUpper(); }
}
}
編輯:根據下面的評論,這里是 Xamarin.Forms 的替代解決方案
這使用值轉換器作為綁定解決方案的一部分。 它也被稍微修改以在下面的評論中使用 clint 的建議。 謝謝。
public class StringCaseConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
switch ((parameter as string).ToUpper()[0])
{
case 'U':
return ((string)value).ToUpper();
case 'L':
return ((string)value).ToLower();
default:
return ((string)value);
};
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
}
它將在 XAML 中使用,如下所示:
Text="{Binding Text, Converter={StaticResource caseConverter}, ConverterParameter=u}}"
或者您可以使用 Bindable 屬性然后格式化 getter 上的文本:例如:
public static readonly BindableProperty ItemLabelProperty =
BindableProperty.Create(nameof(ItemLabel), typeof(string),
typeof(DetailsLineItemControl), default(string), BindingMode.OneWay);
public string ItemLabel
{
get
{
var value = (string)GetValue(ItemLabelProperty);
return !string.IsNullOrEmpty(value) ? value.ToUpper() : value;
}
set
{
SetValue(ItemLabelProperty, value);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.