單一畫面資料來源通常都是相同的,可以透過 BindingContext 統一設定,方便存取。
當在父控制項上設定 BindingContext,會自動傳遞到所有子控制項上,該筆記就是在 ContentPage 上設定 BindingContext,兩個 Entry 就可以直接抓 ContentPage 上的 BindingContext 來使用
C# 內設定 BindingContext
namespace DataBindingPractice
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class Blog1_Simple : ContentPage
{
public Blog1_Simple()
{
InitializeComponent();
var Data = new MemberInfo();
// 設定 BindingContext,並在 Xaml 內設定 txtName DataBinding
this.BindingContext = Data;
// 利用 C# Code 建立 DataBinding
// 方法一
Binding bdEmail = new Binding()
{
Source = Data,
Path = "Email"
};
txtEmail.SetBinding(Entry.TextProperty, bdEmail);
// 方法二
txtEmail.BindingContext = Data;
txtEmail.SetBinding(Entry.TextProperty, nameof(Data.Email));
}
}
}
<?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.Blog1_Simple">
<ContentPage.Content>
<StackLayout VerticalOptions="Center" HorizontalOptions="Center">
<Entry x:Name="txtName" Text="{Binding Path=Name}"></Entry>
<Entry x:Name="txtEmail"></Entry>
</StackLayout>
</ContentPage.Content>
</ContentPage>
在 Xaml 內設定 BindingContext<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:DataBindingPractice"
x:Class="DataBindingPractice.Blog1_Simple">
<ContentPage.BindingContext>
<local:MemberInfo />
</ContentPage.BindingContext>
<ContentPage.Content>
<StackLayout VerticalOptions="Center" HorizontalOptions="Center">
<Entry x:Name="txtName" Text="{Binding Path=Name}"></Entry>
<Entry x:Name="txtEmail" Text="{Binding Path=Email}"></Entry>
</StackLayout>
</ContentPage.Content>
</ContentPage>
擷取 Xamarin 官方文章說明Note: Typically, the runtime performance is better if BindableObject.BindingContext is set after all calls to BindableObject.SetBinding have been made.
沒有留言:
張貼留言