1

情况如下:

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

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

4

1 回答 1

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 }
};
于 2015-10-22T12:04:38.917 回答