绑定按钮路径图像(使用MvxBaseAndroidTargetBinding)Android

时间:2012-10-22 12:53:35

标签: c# mono xamarin.android mvvmcross

如何使用MvxBaseAndroidTargetBinding将路径图像绑定到按钮?

1)我创建了一个绑定

public class MvxButtonIconBinding: MvxBaseAndroidTargetBinding
{
    private readonly View _view;

public MvxButtonIconBinding(View view)
{
    _view = view;
}

public override void SetValue(object value)
{
    string path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
    path = Path.Combine(path, "pictures");
    path = Path.Combine(path, (string)value);
    if (File.Exists(path))
    {
        var dr = Drawable.CreateFromPath(path);
        Button b = _view as Button;
        var drawables = b.GetCompoundDrawables();
        foreach (var d in drawables)
            if (d!=null)
                d.Dispose(); // To avoid "out of memory" messages
        b.SetCompoundDrawablesWithIntrinsicBounds(null, dr, null, null);
    }
    else
    {
        Console.WriteLine("File {0} does not exists", path);
    } 
}

public override MvxBindingMode DefaultMode
{
    get { return MvxBindingMode.OneWay; }
}

public override Type TargetType
{
    get { return typeof(string); }
}

protected override void Dispose(bool isDisposing)
{
    if (isDisposing)
    {
    }
    base.Dispose(isDisposing);
}

}

2)设置绑定:

registry.RegisterFactory(new MvxCustomBindingFactory<View>("ButtonIcon", view => new MvxButtonIconBinding(view)));

3)创建button_list.аxml

<Button
android:id="@+id/ButtonArticle"
android:layout_width="fill_parent"
android:layout_height="160dp"
android:gravity="bottom|center"
android:paddingBottom="5dp"
android:paddingTop="5dp"
local:MvxBind="{'Click':{'Path':'Command1'},'ButtonIcon':{'Path':'Item.PictureFileName'}}"
android:textSize="14dip"
android:textColor="@drawable/ToggleButtonSelector" />

哪个路径传输属性PictureFileName?请给我一个例子。


Taken from

1 个答案:

答案 0 :(得分:0)

从您的代码中,图片应位于:

string path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
path = Path.Combine(path, "pictures");
path = Path.Combine(path, (string)value);

因此,如果您的输入值Item.PictureFileName为'icon1.png',那么您需要保存图片:

/data/data/YOUR_APP_NAME/files/pictures/icon1.png

我根据Database File Location for SQLite within MonoDroid

System.Environment.SpecialFolder.Personal的信息解决了这个问题

如果您使用的是固定图标集(不下载或动态创建图片),那么最好使用the conference sampleSetButtonBackground所示的resourceId方法