处理Xamarin中自定义XAML控件的属性

时间:2016-02-25 04:28:18

标签: c# forms xaml xamarin

我有一个自定义的ContentView(FolioReceiptView),它公开了一个名为“ReceiptMarker”的属性(代码为了清晰而浓缩):

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);
    }
  }
}

我在页面中使用控件,如下所示:

<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>

但是,在类的构造函数中,ReceiptMarker值为null。为什么不从XAML中获取价值?

2 个答案:

答案 0 :(得分:0)

“对象初始化程序允许您在构造对象后设置属性或字段” - 这意味着在构造函数执行结束后分配ReceiptMarker =“A”。

如果希望ReceiptMarker在构造函数中可用,请将其作为参数传递。

答案 1 :(得分:0)

事实证明,我在设置视图模型之前尝试在ViewModel上设置ReceiptMarker。现在一切都已解决。 :)