[英]What is the easiest way to bind a float to a Label Text in Xamarin Forms?
我熟悉Xamarin形式的MVVM和数据绑定。 但是,当前在我的应用程序中,我的ViewModel中有一些浮点值,需要绑定到XAML中的Label的Text。
有什么解决办法吗? 提前致谢。
您在问题中提到了两件事,将浮点数绑定到Label的Text属性,并将“一些浮点值”绑定到Label的Text。
您可以使用以下方法轻松将浮点数绑定到标签:
<Label Text="{Binding YourFloatProperty}" />
或使用StringFormat:
<Label Text="{Binding YourFloatProperty, StringFormat='This is the value: {0:D2}'}" />
如果您要将多个浮点数绑定到标签的文本,目前,无法使用标准Xamarin表单执行此操作。 它被列为GitHub上的增强功能,因此它可能会出现在更高版本中。
您虽然有一些选择。
#1的示例:
string FloatText { get => $"This is the first float: {_float1} and here is the second{_float2}"; }
我建议选择1。
这可能起作用:
Label Text="{Binding YourFloatValue, StringFormat='{0:D2}'}" />
或在后面的代码中:
Label.Text = YourFloatValue.ToString();
最简单的方法是将字符串属性包装在viewmodel中,并使用String.Format()
方法设置值。
我写了一个简单的演示来解释它。 假设您的视图float1
有2个float值: float1
和float2
,则可以添加字符串属性OutputString
并使用以下方法设置其值: this.OutputString = String.Format("Value1 is {0}; Value2 is {1}", Value1, Value2);
然后将标签的文本绑定到OutputString
完整的代码如下所示:
MyViewModel.cs
class MyViewModel : INotifyPropertyChanged
{
float value1;
float value2;
string outputString;
public event PropertyChangedEventHandler PropertyChanged;
public MyViewModel()
{
this.Value1 = 1.1f;
this.Value2 = 1.2f;
this.OutputString = String.Format("Value1 is {0}; Value2 is {1}", Value1, Value2);
}
public float Value1
{
set
{
if (value1 != value)
{
value1 = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("Value1"));
}
}
}
get
{
return value1;
}
}
public float Value2
{
set
{
if (value2 != value)
{
value2 = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("Value2"));
}
}
}
get
{
return value2;
}
}
public string OutputString
{
set
{
if (outputString != value)
{
outputString = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("OutputString"));
}
}
}
get
{
return outputString;
}
}
}
MainPage.xaml:
<ContentPage.BindingContext>
<local:MyViewModel/>
</ContentPage.BindingContext>
<StackLayout>
<!-- Place new controls here -->
<Label Text="{Binding OutputString}"
HorizontalOptions="Center"
VerticalOptions="CenterAndExpand" />
</StackLayout>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.