繁体   English   中英

自定义控件公开子Binadable属性

[英]Custom control expose child binadable property

情况如下:

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

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

替代方法:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM