2021年4月7日星期三

How to access the BindingContext of custom control in Xamarin.Forms

I have a CollectionView with ItemsSource set to ObservableCollection of type Employee. The ItemTemplate of the CollectionView is a CustomControl that has 1 BindableProperty of Type Employee

MainPage.xaml:

  <CollectionView ItemsSource="{Binding Employees}"                    SelectedItem="{Binding SelectedEmployee}">      <CollectionView.ItemTemplate>        <DataTemplate>          <controls:CustomControl Employee="{Binding .}" />        </DataTemplate>      </CollectionView.ItemTemplate>    </CollectionView>  

The CustomControl has an image (checked image to indicate selection).

CustomControl.xaml:

  <Frame HasShadow="True"           BackgroundColor="Blue">      <StackLayout Orientation="Horizontal">        <Label Text="{Binding Name}" />        <Image Source="check.png" />      </StackLayout>    </Frame>  

CustomControl.xaml.cs:

public partial class CustomControl : ContentView      {          public CustomControl()          {              InitializeComponent();          }            public static BindableProperty EmployeeProperty = BindableProperty.Create(                      propertyName: nameof(Employee),                      returnType: typeof(Employee),                      declaringType: typeof(CustomControl),                      defaultValue: default(Employee),                      defaultBindingMode: BindingMode.OneWay);            public Employee Employee          {              get              {                  return (Employee)GetValue(EmployeeProperty);              }              set              {                  SetValue(EmployeeProperty, value);              }          }      }  

Model (Employee):

public class Employee: INotifyPropertyChanged      {          private int name;          public int Name          {              get              {                  return name;              }              set              {                  name = value;                  OnPropertyChanged(nameof(Name));              }          }              private int isSelected;          public int IsSelected          {              get              {                  return isSelected;              }              set              {                  isSelected = value;                  OnPropertyChanged(nameof(IsSelected));              }          }            #region PropertyChanged          public void OnPropertyChanged(string propertyName)          {              PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));          }            public event PropertyChangedEventHandler PropertyChanged;          

没有评论:

发表评论