【问题标题】:Xamarin.Forms SetBinding to Image so that it refreshes when its Source changesXamarin.Forms SetBinding to Image 以便在其 Source 更改时刷新
【发布时间】:2017-06-02 03:45:51
【问题描述】:

当我更改它们的 ImageSource 时,我正在尝试更新/重新绘制页面中的图像 - 这将帮助我让它们异步重新加载。

我认为为 imageSource 绑定到图像的可绑定属性是一个开始,但它并没有更新图像。我尝试了很多方法,包括带有 OnPropertyChanged 事件的 viewModel 方法,但我认为我不太了解这一点。

此绑定也必须在代码中完成,这就是应用程序的编写方式(最小 xaml)。

到目前为止,我的一般做法是:

可绑定属性

public static readonly BindableProperty ImageFileProperty = BindableProperty.Create("ImageProperty", typeof(string), typeof(CustomImageClass));

public string ImageProperty { get { return (string)GetValue(ImageFileProperty); } set { SetValue(ImageFileProperty, value); } }

CustomImageClass 构造函数内部:

this.SetBinding(ImageFileProperty, "ImageProperty");

从这里我希望在更新 ImageSource 并更改图像时更改图像。我希望这足够具体,我认为绑定到 xaml 的所有不同示例都让我感到困惑,因为我需要在代码中执行它。

【问题讨论】:

    标签: c# xamarin.forms bindable


    【解决方案1】:

    对不起英语不好

    我猜这里有很多问题......

    如果我理解得很好,您想在您的 CustomImageClass 中创建一个 BindableProperty。是对的吗? 如果是,那么您可以对可绑定属性名称使用默认约定,如下所示(注意我也更改了类型):

    public static readonly BindableProperty ImageFileProperty =
            BindableProperty.Create("ImageFile", typeof(ImageSource), 
            typeof(CustomImageClass));
    
    public ImageSource ImageFile
    {
        get{ return (string)GetValue(ImageFileProperty); }
        set{ SetValue(ImageFileProperty, value); }
    }
    

    您不能将绑定设置为您刚刚在构造函数中创建的属性。这将在您使用该类时使用(在 xaml 或 c# 中)。

    现在您必须使用您的属性来设置您想要显示的图像。我认为你应该在这个类中有一个 Image 类型的变量或私有属性,例如'image',所以,在构造函数中你应该这样做

    image = new Image();
    image.BindingContext = this;
    image.SetBinding(Image.Source, nameof(ImageFile));
    

    如果我理解错了,请告诉我。 希望对你有帮助。

    【讨论】:

    • 非常感谢迭戈!不,你的英文解释很好。我没有正确添加您为我指出正确方法的 BindingContext。这对我来说现在很好。对于使用 PropertyBindings 未获得预期结果的人来说,另一件需要注意的事情 - 当我尝试让此代码最初正常工作时,我的图像没有正确更改,但是在从测试设备中彻底​​删除应用程序后,图像恢复正常.可能的缓存类型问题。
    猜你喜欢
    • 2015-08-31
    • 1970-01-01
    • 2022-08-20
    • 2011-11-22
    • 2012-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-09
    相关资源
    最近更新 更多