如何将绑定上下文标签值保存为xamarin表单中的字符串

时间:2017-03-24 10:02:44

标签: listview xamarin binding xamarin.forms label

ListView listView = new ListView();
listView.ItemTemplate = new DataTemplate(typeof(CustomVeggieCell));
listView.ItemsSource = sample;
Content = new StackLayout
{
    Children ={
        listView,
    }
};


public class CustomVeggieCell : ViewCell
{
public CustomVeggieCell()
{
        var image = new Image();
        var typeLabel = new Label { };


        typeLabel.SetBinding(Label.TextProperty, new Binding("contact"));

        var string = typeLabel.Text;

        if (typeLabel.Text == "Send")
        {
            image.Source = "Send.png";
        }
        else
        {
            image.Source = "draft.png";
        }


        var horizontalLayout = new StackLayout();
        horizontalLayout.Children.Add(image);


        View = horizontalLayout;

    }
}

我在Xamarin表单中创建了一个带有Json Web服务响应的列表视图。我需要根据值显示图像。 绑定值无法存储在字符串中。它总是返回null。我想存储绑定标签文本。何实现这个?

1 个答案:

答案 0 :(得分:1)

您可以使用IValueConverter

这样的东西
public class CustomVeggieCell : ViewCell
{
    public CustomVeggieCell()
    {
        var image = new Image();

        image.SetBinding(Image.SourceProperty, new Binding("contact", BindingMode.Default, new ConvertTextToSource()));

        var horizontalLayout = new StackLayout();
        horizontalLayout.Children.Add(image);


        View = horizontalLayout;

    }

}

然后转换器

        public class ConvertTextToSource : IValueConverter
        {

            #region IValueConverter implementation

            public object Convert (object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
            {
                if ( value != null &&  value is string )  {

                    string text = ((string)value);

                    if (text == "Send")
                    {
                        return "Send.png";
                    }
                    else
                    {
                        return "draft.png";
                    }
                }
                return "";
            }

            public object ConvertBack (object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
            {
                throw new NotImplementedException ();
            }

            #endregion
        }

应该有效