【问题标题】:How to initialise a bindable property of type Array from XAML如何从 XAML 初始化 Array 类型的可绑定属性
【发布时间】:2020-07-25 04:45:38
【问题描述】:



在自定义组件中,我定义了一个 ARRAY 类型的可绑定属性:

public static BindableProperty LabelsProperty = BindableProperty.Create(nameof(LabelStrings), typeof(string[]), typeof(BLSelector), null, BindingMode.Default, propertyChanged: OnLabelsPropertyChanged);
public string[] LabelStrings
{
    get => (string[])GetValue(LabelsProperty);
    set => SetValue(LabelsProperty, value);
}
private static void OnLabelsPropertyChanged(BindableObject bindable, object oldValue, object newValue)
{
    var current = bindable as BLSelector;

    // Check the number of strings
    if (current.Commands != null && current.LabelStrings.Count() != current.Commands.Count())
    {
        Debug.WriteLine("Component::BLSelector - Bad number of Labels");
        throw new TargetParameterCountException();
    }

    // Updates the number of Label Controls
    current.LabelControls = new Label[current.LabelStrings.Count()];

    // Set up the layout
    current.GridContendUpdate();
}

我想使用 XAML 文件中的这个组件,因此像这样设置这个属性:

        <components:BLSelector>
            <components:BLSelector.LabelStrings>
                <x:Array Type="{x:Type x:String}">
                    <x:String>"           Activités            "</x:String>
                    <x:String>"          Prestations           "</x:String>
                </x:Array>
            </components:BLSelector.LabelStrings>
        </components:BLSelector>

当我启动应用程序时,应用程序在没有消息的情况下崩溃(由于空引用?)。如果在设置器上放置一个断点,我可以看到它永远不会被调用。
但是......如果我在组件的构造函数中添加一个“内部”初始化,如下所示,setter 被调用两次(来自内部声明和 XAML 文件的数据 - 这是正常的)并且应用程序执行不会崩溃。

public BLSelector()
{
    InitializeComponent();

    LabelStrings = new string[2]{ "Test 1", "Test 2" };
}

如果我只将属性分配给 XAML 文件中定义的数组,为什么应用程序会崩溃? XAML 中真正的数组类型是什么?有初始化问题吗?任何的想法 ?

非常感谢您的建议

【问题讨论】:

  • 你想在这里做什么?在 Label 的 Text 上显示数组项?
  • 我的 BLSelector 组件是一个为用户提供一种选择的组件。 LabelStrings 属性是要提议的菜单项(字符串)的列表。我想在 XAML 中定义我使用这个组件的字符串数组作为菜单绑定传递给属性。

标签: arrays xamarin xamarin.forms bindableproperty


【解决方案1】:

可绑定属性的命名约定是 属性标识符必须与在 Create 方法,附加了 "Property"。 所以尝试更改您的可绑定属性名称:

public static BindableProperty LabelStringsProperty = BindableProperty.Create(nameof(LabelStrings), typeof(string[]), typeof(BLSelector), null, BindingMode.Default, propertyChanged: OnLabelsPropertyChanged);

【讨论】:

  • 天哪,怎么可能错过这个!太棒了...非常感谢您仔细阅读我的帖子。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-03
  • 2020-08-06
  • 2021-08-20
  • 1970-01-01
  • 1970-01-01
  • 2021-10-13
相关资源
最近更新 更多