MVVMCross 更新绑定到 UITableViewCell

3
我想知道我是否正确地做了这件事-这种方法是可行的,但感觉有点“不好”,本质上,MvxTableViewCell的一个按钮会改变绑定对象的参数,但是在滚动视图离开并重新进入视图之前(即单元格被‘重绘’之前),该单元格不会更新以反映更改。所有这里的示例都是简化的,但你可以理解其中的思路。
首先,我的对象:
public class Expense
{
    public decimal Amount { get; set; }
    public bool Selected { get; set; }
    public Command FlipSelected
    {
        get { return new MvxCommand(()=> this.Selected = !this.Selected); }
    }
}

其次,在我的构造函数中,我的单元格包含:
this.DelayBind(() =>
{
    var set = this.CreateBindingSet<HistoryCell, Expense>();
    set.Bind(this.TitleText).To(x => x.Amount);
    set.Bind(this.SelectButton).To(x=> x.FlipSelected);
    set.Bind(this.SelectButton).For(x => x.BackgroundColor).To(x => x.Selected).WithConversion(new ButtonConverter(), null);
    set.Apply();
});

我有一个值转换器,返回按钮的背景颜色:

class ButtonConverter : MvxValueConverter<bool, UIColor>
{
    UIColor selectedColour = UIColor.FromRGB(128, 128, 128);
    UIColor unSelectedColour = UIColor.GroupTableViewBackgroundColor;
    protected override UIColor Convert(bool value, Type targetType, object parameter, CultureInfo culture)
    {
        return value ? selectedColour : unSelectedColour;
    }
    protected override bool ConvertBack(UIColor value, Type targetType, object parameter, CultureInfo culture)
    {
        return value == selectedColour;
    }
}

好的,那么发生的情况是,如果我点击单元格中的按钮,它会运行命令来翻转布尔值Selected,这个值绑定回单元格背景颜色通过 ButtonConverter 值转换器。

我的问题在于,单元格并没有立即更新,只有当我滚动视图使该单元格移出视图然后再次进入时才会更新(即单元格被重新绘制)。因此,我认为我只需要让单元格变得“脏”:

        this.SelectButton.TouchUpInside += (o, e) =>
        {
            this.SetNeedsDisplay();
        };

但这并不起作用。真正有效的方法是在TouchUpInside事件中添加其他代码来手动更改背景颜色。但我假设这不是正确的做法。
当我更改Expense对象中的Selected值时,是否需要触发RaisePropertyChanged?当它只是一个对象时我该怎么做呢?
真的很希望斯图尔特可以在这个问题上提供帮助 ;)
1个回答

6

我认为你的分析是正确的——UI没有实时更新,因为Expense对象中没有变化消息。

要在视图模型对象中提供“传统”的更改通知,您需要确保每个对象都支持INotifyPropertyChanged。如果您愿意,可以很容易地自己实现这个小接口——或者如果您愿意,可以修改Expense以继承内置的MvxNotifyPropertyChanged助手类——然后RaisePropertyChanged将可用。

作为另一种选择,如果您愿意,也可以实现基于'Rio'字段的新绑定方法。有关此功能的介绍,请参见http://mvvmcross.blogspot.com中的N=36。


再次感谢你,Stuart!顺便问一下,你有没有关于如何绑定UIButtonCurrentBackgroundImage的建议?(我正在使用一个转换工具)它显示“无法为CurrentBackgroundImage创建目标绑定”。 - benpage

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接