簡體   English   中英

Xaml使用隱藏屬性

[英]Xaml using hidden property

我做了一個自定義控件,它具有屬性X隱藏了父級的VisualElement.X屬性。

public class MyCustomControl : ContentView // is a distant child of VisualElement
{
    public new double X
    {
        get { return 0; }
        set { Console.WriteLine("I was not called with: " + value); }
    }
}

我在xaml中設置了自定義控件的X

<controls:MyCustomControl X="10" />

但是,在此調用了Xamarin.Forms.VisualElement.X屬性設置器,而不是MyCustomControl.X設置器。 為什么? 以及如何使它改為使用我的自定義控件屬性?


作為旁注。 x:Name="myCustomControl並且myCustomControl.X = 10在后面的代碼中時-則調用MyCustomControl的setter。


聲明父級中不存在的屬性時:

public double AnotherX
{
    get { return 0; }
    set { Console.WriteLine("Was called with: " + value); }
}

設置員被稱為。 (來自xaml)。

這是因為您正在通過Xaml設置VisualElement的BindableProperty'X'。 如果您還在自定義控件中創建BindableProperty'X',它也應該起作用。

  1. 您不應該嘗試覆蓋X,而應該使用新名稱
  2. 您創建一個bindableproperty不僅是一個屬性,請參見下面的如何制作一個可綁定屬性

     private readonly BindableProperty CustomXProperty = BindableProperty.Create(nameof(CustomX), typeof(double), typeof(MyCustomControl), defaultValue: 0.0); public double CustomX { get { return (double)GetValue(CustomXProperty); } set { SetValue(CustomXProperty, value); } } 

請參閱此處以獲取更多信息https://docs.microsoft.com/zh-cn/xamarin/xamarin-forms/xaml/bindable-properties

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM