【问题标题】:Bind Drawable Background Color with MVVM light in Xamarin.Android在 Xamarin.Android 中将可绘制背景颜色与 MVVM 灯光绑定
【发布时间】:2016-10-09 21:10:34
【问题描述】:

我在我的 Xamarin.Android 项目中使用 MVVM 灯,并希望将我的 MainViewModelStatusColor 属性绑定到作为 ImageView 控件背景的 GradientDrawable 的背景。

不幸的是,GradientDrawable 没有我可以将颜色绑定到的任何 Color 属性,只有 SetColor(int) 方法。有没有办法告诉 MVVM light 在我的MainViewModelStatusColor 属性发生变化时始终调用这个SetColor(int) 方法?

丑陋的(!)替代方法是在 ViewModel 更改颜色属性时触发事件,但我真的想避免这种情况......

我的代码目前如下所示:

// This does not work!
this.SetBinding(
    () => MainViewModel.StatusColor,
    () => ((GradientDrawable)IvStatus.Background).Color); // There is no GradientDrawable.Color property...

如果有帮助,这是我的 IvStatus 控件,Drawable 其背景设置为:

IvStatus:

<ImageView
    android:id="@+id/ivStatus"
    android:background="@drawable/Circle"                                    
    android:layout_width="10dip"
    android:layout_height="10dip"
    android:layout_gravity="center_vertical" />

Circle.xml:

<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">
    <solid android:color="#cccccc"/>
    <stroke
        android:width="1dip"
        android:color="#333333"/>
</shape>

【问题讨论】:

  • 我不认为你可以。也许看看 MvvmCross 库,他们可能有一个绑定解决方法。但据我所知,对于 MvvmLight,您应该只在您的 android 应用程序中订阅属性更改事件,并在您的 VM 中颜色值发生更改时手动创建一个新的 GradientBrush

标签: mvvm xamarin binding xamarin.android mvvm-light


【解决方案1】:

使用 Binding.WhenSourceChanges 方法。

this.SetBinding(
    () => MainViewModel.StatusColor)
    .WhenSourceChanges(() =>
        {
            // This is where you can use SetColor
        });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多