MonoTouch.Dialog: Update of Text in an Element

2019-05-26 13:13发布

问题:

Using MonoTouch.Dialog I add StyledStringElement elements.

There is a background task that retrieves details that need to update the element.Value

Is there a way to force the element to have it's text updated after the element.Value is updated?

Ian

回答1:

If you want to update this element-by-element then you can use something like:

public class MyStyledStringElement {

    public void SetValueAndUpdate (string value)
    {
        Value = value;
        if (GetContainerTableView () != null) {
            var root = GetImmediateRootElement ();
            root.Reload (this, UITableViewRowAnimation.Fade);
        }
    }
}

A variation would be to load everything and update once (i.e. iterating on the root.Reload for every Element).



回答2:

I've added "this.PrepareCell (cell); to the SetValueAndUpdate method and works. But I still thinking in that there is another better option detecting the change of "caption" and calling this.PrepareCell (cell);.

public void UpdateCaption(string caption) {
        this.Caption = caption;
        Console.WriteLine ("actualizando : " + Caption);
        UITableViewCell cell = this.GetActiveCell ();
        if (cell != null) {
            this.PrepareCell (cell);
            cell.SetNeedsLayout ();
        }
}


回答3:

Another approach to update the label would be to derive from StyledStringElement or StringElement and directly refresh the DetailTextLabel within the cell:

class UpdateableStringElement : StringElement
{
    public UpdateableStringElement(string name): base (name)
    {
    }

    UILabel DetailText = null;

    public void UpdateValue(string text)
    {
        Value = text;
        if (DetailText != null)
            DetailText.Text = text;
    }

    public override UITableViewCell GetCell(UITableView tv)
    {
        var cell = base.GetCell(tv);
        DetailText = cell.DetailTextLabel;
        return cell;
    }
}

Instead of the Value property you can then use the UpdateValue method:

var element = new UpdateableStringElement("demo");

SomeEventOfYours += delegate {
    element.UpdateValue(LocalizedValue);
};