首页 > 解决方案 > 如何使用 BindableProperty.Create 在 Xamarin 中为绑定创建默认值?

问题描述

我创建了一个模板来制作标签:

<?xml version="1.0" encoding="utf-8"?>
<Grid Padding="20,0" xmlns="http://xamarin.com/schemas/2014/forms" 
      xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
      xmlns:local="clr-namespace:Test;assembly=Test" 
      x:Class="Test.MyTemplate" 
      x:Name="this" >
    <Label Grid.Column="1" 
           IsVisible="{Binding LabelVisible, Source={x:Reference this}}"
           Text="Test" />
</Grid>

public partial class MyTemplate : Grid
{

    public event EventHandler Action;

    public MyTemplate()
    {
        InitializeComponent();
    }

    public static readonly BindableProperty LabelVisibleProperty =
        BindableProperty.Create(
            nameof(LabelVisible),
            typeof(bool),
            typeof(MyTemplate),
            true); // << I set this to true as I think it is for the default setting

    public bool LabelVisible
    {
        get { return (bool)GetValue(LabelVisibleProperty); }
        set { SetValue(LabelVisibleProperty, value); }
    }

}

如果我在页面中对此进行编码,我希望它默认为 true 值:

<template:MyTemplate />

但是即使将 BindableProperty.Create 的最后一个属性设置为 true,我的标签仍然不可见(我认为这是我设置默认值的地方)。

我没有正确设置默认值吗?

标签: xamarinxamarin.forms

解决方案


我猜 UI 没有收到LabelVisible更新的通知,也没有相应地更新IsVisible。要么实现INotifyPropertyChanged接口,要么将propertyChanged参数添加到您的BindableProperty.Create调用中。

后者可以这样做:

public static readonly BindableProperty LabelVisibleProperty =
    BindableProperty.Create(
        nameof(LabelVisible),
        typeof(bool),
        typeof(DataGridTemplate),
        true, onPropertyChanged: OnLabelVisiblePropertyChanged);

并实现这样的方法:

private static void OnLabelVisiblePropertyChanged(BindableObject bindable, object oldValue, object newValue)
{
    if (bindable != null && bindable is DataGridTemplate template)
        template.MyLabel.IsVisible = (bool)newValue;
}

你必须给你Label一个x:Name值,并且绑定在那个时候并没有真正做太多:<Label x:Name="MyLabel" Grid.Column="1" Text="Test" />


推荐阅读