C# 使用隐藏属性的Xaml

C# 使用隐藏属性的Xaml,c#,xaml,inheritance,xamarin.forms,properties,C#,Xaml,Inheritance,Xamarin.forms,Properties,我制作了一个自定义控件,它有一个属性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: " + valu

我制作了一个自定义控件,它有一个属性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" />

设定者被称为。这是因为您正在通过xaml设置VisualElement的BindableProperty“X”。
如果您在自定义控件中创建BindableProperty“X”,它也会起作用。

这是因为您正在通过Xaml设置VisualElement的BindableProperty“X”。 如果您在自定义控件中创建BindableProperty“X”,它也应该可以工作

您不应该试图覆盖X,您应该使用新名称 您可以创建一个bindableproperty,而不仅仅是一个属性。有关如何创建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);
    }
}
请参阅此处了解更多信息

您不应该试图覆盖X,您应该使用新名称 您可以创建一个bindableproperty,而不仅仅是一个属性。有关如何创建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);
    }
}

有关更多信息,请参见此处

设置器仍未调用。我注意到之前有必要申报财产变更。此外,xaml BindablePropertys中的所有属性都可以访问吗?完全不使用普通属性?不,我可以在自定义控件中定义一个不存在父级的属性,该属性在xaml中可见。这个属性的setter将被调用。但是我假设xaml首先要查找BindableProperty,然后才是普通属性。我有点不明白你在问什么?setter仍然没有被调用。我注意到之前有必要申报财产变更。此外,xaml BindablePropertys中的所有属性都可以访问吗?完全不使用普通属性?不,我可以在自定义控件中定义一个不存在父级的属性,该属性在xaml中可见。这个属性的setter将被调用。但是我假设xaml首先要查找BindableProperty,然后才是普通属性。我有点不明白你在问什么?演示如何隐藏BindableProperty。它这样做是为了覆盖默认值。但是xaml是否首先查找BindableProperties呢?在这种情况下,BindableProperty似乎将该属性隐藏在自定义控件中。我可以告诉xaml先查找子属性吗。有没有不在child中声明BindableProperty的解决方案?演示如何隐藏BindableProperty。它这样做是为了覆盖默认值。但是xaml是否首先查找BindableProperties呢?在这种情况下,BindableProperty似乎将该属性隐藏在自定义控件中。我可以告诉xaml先查找子属性吗。有没有不在child中声明BindableProperty的解决方案?