情况如下:
我创建了一个自定义控件,其中包含一个ImageView。 我希望能够在使用自定义控件时从XAML绑定此子视图的属性(IsVisible),但我不确定如何在父自定义控件中公开此属性。
我想设置这样的东西(IsLeftImageVisible应该是暴露的子控件属性):
<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); }
}
有没有办法更优雅地做到这一点?
答案 0 :(得分:1)
执行此操作的替代方法:
来自渲染器:
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 }
};