简体   繁体   中英

Handling Attributes on Custom XAML Controls in Xamarin

I have a custom ContentView (FolioReceiptView) that exposes a property called "ReceiptMarker" (Code condensed for clarity):

public partial class FolioReceiptView : ContentView {
  public FolioReceiptView() {
    InitializeComponent ();
    if (!String.IsNullOrWhiteSpace (ReceiptMarker)) {
      var vm = BindingContext as FolioReceiptViewModel;
      if (vm != null) {
        vm.Marker = ReceiptMarker;
      }
    }
  }

  public static readonly BindableProperty ReceiptMarkerProperty = BindableProperty.Create ("ReceiptMarker", typeof(string), typeof(FolioReceiptView), null);

  public string ReceiptMarker { 
    get {
      return (string)GetValue (ReceiptMarkerProperty);
    } 
    set {
      SetValue (ReceiptMarkerProperty, value);
    }
  }
}

I use the control in a Page like so:

<StackLayout Orientation="Horizontal" HorizontalOptions="FillAndExpand" Spacing="10" VerticalOptions="FillAndExpand">
  <view:FolioReceiptView x:Name="ReceiptA" ReceiptMarker="A" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand" />
  <view:FolioReceiptView x:Name="ReceiptB" ReceiptMarker="B" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand" />
  <view:FolioReceiptView x:Name="ReceiptC" ReceiptMarker="C" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand" />
</StackLayout>

However, in the class's constructor, the ReceiptMarker value is null. Why isn't the value picked up from the XAML?

"An Object Initializer lets you set properties or fields on your object after it's been constructed" - that means you assign ReceiptMarker="A" after constructor execution ends.

If you want ReceiptMarker to be available in constructor, pass it as argument.

As it turns out, I was trying to set the ReceiptMarker on the ViewModel before the view model was set. All is fixed now. :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM