【问题标题】:How to save binding context label value to a string in xamarin forms如何将绑定上下文标签值保存到 xamarin 表单中的字符串
【发布时间】:2017-08-17 05:07:26
【问题描述】:
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。我想存储绑定标签文本。何能做到这一点?

【问题讨论】:

    标签: listview xamarin binding xamarin.forms label


    【解决方案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
            }
    

    应该可以的

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-15
      • 2020-02-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多