星期五, 7月 28, 2017

[X.Form] DataBinding - StringFormat

當 Source 資訊沒有辦法滿足 UI 上呈現需求,可以透過 Binding 的 StringFormat 功能來達成

[X.Form] DataBinding - StringFormat-2

StringFormatData Class
namespace DataBindingPractice
{
    public class StringFormatData
    {
        public string EmpName { get; set; }
        public decimal Salary { get; set; }
        public DateTime HireDate { get; set; }

        public StringFormatData()
        {
            EmpName = "Xamarin";
            Salary = 49000;
            HireDate = new DateTime(2008,3,3);
        }
    }
}
C# 內設定
namespace DataBindingPractice
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class XF6_StringFormat : ContentPage
    {
        public XF6_StringFormat()
        {
            var Data = new StringFormatData();
            BindingContext = Data;

            InitializeComponent ();

            lblEmpName.SetBinding(Label.TextProperty, nameof(Data.EmpName), stringFormat: "員工:{0}");
            lblHireDate.SetBinding(Label.TextProperty, nameof(Data.HireDate), stringFormat: "到職日:{0:yyyy-MM-dd}");
            lblSalary.SetBinding(Label.TextProperty, nameof(Data.Salary), stringFormat: "薪資:NT {0:N0}");
        }
    }
}
Xaml 內設定
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="DataBindingPractice.XF6_StringFormat">
    <ContentPage.Content>
        <StackLayout HorizontalOptions="Center" VerticalOptions="Center">
            <Label x:Name="lblEmpName" Text="{Binding EmpName, StringFormat='員工:{0}'}" FontSize="Large"></Label>
            <Label x:Name="lblHireDate" Text="{Binding HireDate, StringFormat='到職日:{0:yyyy-MM-dd}'}" FontSize="Large"></Label>
            <Label x:Name="lblSalary" Text="{Binding Salary, StringFormat='薪資:NT {0:N0}'}" FontSize="Large"></Label>
        </StackLayout>
    </ContentPage.Content>
</ContentPage>
[X.Form] DataBinding - StringFormat

沒有留言:

張貼留言