【问题标题】:Custom control expose child binadable property in Xamarin Forms自定义控件公开子可绑定属性
【发布时间】:2015-10-21 10:00:01
【问题描述】:

情况如下:

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

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

【问题讨论】:

  • 为什么不优雅?这就是您创建BindableProperty 的方式。尽管我想知道您是否真的需要可绑定属性,因为您没有在示例代码中将其与绑定一起使用。如果您不打算绑定到它,只需创建一个普通属性并在集合中显示或隐藏您的图像。也许这对你来说看起来更优雅?
  • 请参阅"Should questions include “tags” in their titles?",其中的共识是“不,他们不应该”!
  • @GeraldVersluis - 当然我要绑定属性,这只是一个例子

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


【解决方案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 }
};

【讨论】:

    猜你喜欢
    • 2011-10-20
    • 2011-05-11
    • 2015-04-01
    • 2013-12-17
    • 1970-01-01
    • 2012-08-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多