简体   繁体   English

Xaml使用隐藏属性

[英]Xaml using hidden property

I have made a custom control which has a property X - which hides the VisualElement.X property of parent. 我做了一个自定义控件,它具有属性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); }
    }
}

I set the X of the custom control in xaml: 我在xaml中设置了自定义控件的X

<controls:MyCustomControl X="10" />

But here the Xamarin.Forms.VisualElement.X property setter is called instead of the MyCustomControl.X setter. 但是,在此调用了Xamarin.Forms.VisualElement.X属性设置器,而不是MyCustomControl.X设置器。 Why? 为什么? And how can I make it so my custom control property is used instead? 以及如何使它改为使用我的自定义控件属性?


As a side note. 作为旁注。 When x:Name="myCustomControl and myCustomControl.X = 10 in code behind - then the setter of MyCustomControl is called. x:Name="myCustomControl并且myCustomControl.X = 10在后面的代码中时-则调用MyCustomControl的setter。


When declaring property that does not exist in parent: 声明父级中不存在的属性时:

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

the setter is called. 设置员被称为。 (From xaml). (来自xaml)。

This is because you are setting the BindableProperty 'X' of the VisualElement through the Xaml. 这是因为您正在通过Xaml设置VisualElement的BindableProperty'X'。 It should work if you create a BindableProperty 'X' in your custom control as well. 如果您还在自定义控件中创建BindableProperty'X',它也应该起作用。

  1. You shouldn't be trying to override X you should be using a new name 您不应该尝试覆盖X,而应该使用新名称
  2. you create a bindableproperty not just a property see below on how to make a bindable property 您创建一个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); } } 

Please see here for more information https://docs.microsoft.com/en-us/xamarin/xamarin-forms/xaml/bindable-properties 请参阅此处以获取更多信息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