自定义控件在Xamarin窗体中显示子可绑定属性
本文关键字:绑定 属性 显示 Xamarin 窗体 自定义控件 | 更新日期: 2023-09-27 18:18:35
情况如下:
我已经创建了一个自定义控件,其中包含其他子控件中的ImageView。当使用自定义控件时,我希望能够从XAML绑定此子视图的属性(IsVisible),但我不确定如何在父自定义控件中暴露此属性。
我想设置这样的东西(其中isleftimagvisible应该是暴露的子控件属性):
<controls:StepIndicator IsLeftImageVisible="{Binding IsValid}" />
目前我已经做了这样的事情,但我不是很喜欢它:
public static readonly BindableProperty IsLeftButtonVisibleProperty =
BindableProperty.Create<StepIndicator, bool>
(x => x.IsLeftImageVisible, true, propertyChanged: ((
bindable, value, newValue) =>
{
var control = (StepIndicator)bindable;
control.ImageLeft.IsVisible = newValue;
}));
public bool IsLeftImageVisible
{
get { return (bool)GetValue(IsLeftImageVisibleProperty); }
set { SetValue(IsLeftImageVisibleProperty, value); }
}
有没有更优雅的方法?
另一种方法:
- 将LeftImage更改为私有字段
- 使用OnElementPropertyChanged(从渲染器)或OnPropertyChanged(从共享类)
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == StepIndicator.IsLeftButtonVisibleProperty.PropertyName)
{
// do something
}
}
来自共享类:
protected override void OnPropertyChanged(string propertyName)
{
base.OnPropertyChanged(propertyName);
if (propertyName == StepIndicator.IsLeftButtonVisibleProperty.PropertyName)
{
this.imageLeft.IsVisible = newValue;
}
}
或者订阅PropertyChanged事件:
PropertyChanged += (sender, e) => {
if (e.PropertyName == StepIndicator.IsLeftButtonVisibleProperty.PropertyName) { // do something }
};