xamarin - 如何使用 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,我的标签仍然不可见(我认为这是我设置默认值的地方)。
我没有正确设置默认值吗?
解决方案
我猜 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" />
推荐阅读
- inno-setup - 如何在单个 Inno Setup 安装程序中添加 x86 和 x64 VC++ 2019 Redistributables?
- python - Python 正则表达式从字符串中间删除特殊字符并忽略其他任何内容
- python - 如何将链表的最后一个元素移动到python中的第一个元素(下面的代码)?
- javascript - Divs被切断了?
- c++ - 混合 Rcpp 模块和 Rcpp::export
- java - TabLayout 迁移到 AndroidX
- python - 如何在python中的zip文件夹中创建文件?
- c++ - 如何在 Cython 中链接嵌套的 C++ 库
- javascript - 使用 laravel 中的 db 数据更改 tui-calender 中的数据
- reactjs - ReactJS D3 - 如何放大 D3 地理世界地图