自定义控件公开子binadable属性

时间:2015-10-21 10:00:01

标签: c# xaml xamarin xamarin.forms xamarin-forms

情况如下:

我创建了一个自定义控件,其中包含一个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); }
    }

有没有办法更优雅地做到这一点?

1 个答案:

答案 0 :(得分:1)

执行此操作的替代方法:

  • 将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 }
};