【问题标题】:Xamarin Forms binding to nested property not workingXamarin Forms 绑定到嵌套属性不起作用
【发布时间】:2020-08-29 19:58:21
【问题描述】:

除了 Microsoft 文档,我还参考了这个 SO 问题:Xamarin Forms Databinding "." separator

xaml:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage 
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:d="http://xamarin.com/schemas/2014/forms/design"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    xmlns:local="clr-namespace:NAS.App.Framework"
    x:Class="NAS.App.Pages.Complications"
    ControlTemplate="{StaticResource ContentPageTemplate}">
    <ContentPage.Content>
        <StackLayout>
            <CheckBox IsChecked="{Binding InnerProperty1.NestedValue}" />
            <CheckBox IsChecked="{Binding InnerProperty1Checked}" />
            <Label Text="{Binding InnerProperty1.NestedLabel}" />
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

背后的代码:

using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace NAS.App.Pages
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class Complications : ContentPage
    {
        public Complications()
        {
            InitializeComponent();
            InnerProperty1 = new NestedProperty("InnerProperty1");

            BindingContext = this;
        }

        public bool InnerProperty1Checked
        {
            get { return InnerProperty1.NestedValue; }
            set { InnerProperty1.NestedValue = value; }
        }

        public NestedProperty InnerProperty1;
    }

    public class NestedProperty
    {
        public NestedProperty(string label)
        {
            NestedLabel = label;
        }

        private bool _value;
        public bool NestedValue
        {
            get { return _value; }
            set
            {
                _value = value;
            }
        }

        public string NestedLabel { get; private set; }
    }
}

根据 MS 文档和参考文章,我希望绑定到 InnerProperty1.NestedLabel 的 Label 元素显示文本“InnerProperty1”(传递给 NestedProperty 构造函数)。 Label 元素不显示任何内容 - 绑定不起作用。

我还希望在我选中或取消选中第一个 Checkbox 元素时调用 NestedProperty.NestedValue 的设置器。 “_value = value;”上的断点线不打。绑定在这里也不起作用。

我使用直接属性 InnerPropert1Checked 包装 InnerProperty,并将第二个 Checkbox 元素绑定到该属性。当我选中/取消选中第二个复选框时,断点被命中。绑定到非嵌套属性确实有效。

我无法解释为什么绑定到嵌套属性不起作用。

Xamarin 表单 4.6.0.726

此外,页面是在 App.xaml 中定义的 ControlTemplate 的 ContentPresenter 部分。该页面是 AppShell.xaml 中的一个 ShellContent 元素。鉴于非嵌套绑定正在工作,我不确定其中任何一个将如何发挥作用。但也许我在那里遗漏了一些东西。

有什么想法吗?谢谢。

【问题讨论】:

  • 您只能绑定到公共属性。 InnerProperty1 不是属性,因为它没有 get

标签: c# xamarin xamarin.forms binding


【解决方案1】:

您只能绑定到公共属性

InnerProperty1 是一个字段,而不是一个属性

public NestedProperty InnerProperty1;

添加get 使其成为属性

public NestedProperty InnerProperty1 { get; set; }

【讨论】:

    猜你喜欢
    • 2017-07-27
    • 2023-03-24
    • 2017-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-23
    • 2018-09-09
    相关资源
    最近更新 更多