繁体   English   中英

Xamarin窗体具有两个对象的ListView数据绑定

[英]Xamarin Forms ListView Data Binding with two objects

我正在创建天气预报应用程序。 我已经创建了以TextCell作为条目的ListView 我想将单元格内部的测试格式设置为XXX YY ,其中:

  • XXX很有价值
  • YY为单位

我在ContentPage声明了可观察的集合,这是我的ItemSource ,我还有另一个重要的属性weatherUnit

private ObservableCollection<ForecastData> forecast = new ObservableCollection<ForecastData>();
private Unit weatherUnit { get; set; }

我正在构造函数中创建数据模板并设置所有内容:

public WeatherFormsAppPage()
{
    InitializeComponent();
    var forecastWeatherDataTemplate = new DataTemplate(typeof(TextCell));
    forecastWeatherDataTemplate.SetBinding(TextCell.TextProperty, "mainData.Temperature");
    forecastWeatherDataTemplate.SetBinding(TextCell.DetailProperty, "date");
    ForecastView.ItemsSource = forecast;
    ForecastView.ItemTemplate = forecastWeatherDataTemplate;
}

如何将TextCell.TextProperty绑定格式添加为temperature和weatherUnit。 温度是两倍,天气单位具有返回String的Extension。 现在,只有温度值正确显示,并且日期显示为详细信息:

当前状态

您可以创建一个只读属性,为您合并值,然后将其绑定到该属性。

public string WeatherData 
{
    get
    {
        return $"{Temperature} {Unit}";
    }
}

捆绑

forecastWeatherDataTemplate.SetBinding(TextCell.TextProperty, "mainData.WeatherData ");

我也喜欢戴维的方法。 无需担心在JSON类中具有仅获取属性。 由于您不想那样做,您还可以编写一个转换器类并将其添加到绑定中。

public class StringToFormattedTempConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (!(value is string))
            return value;

        return $"{(string)value} \u00B0CC";        
    }

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

然后将其添加到这样的绑定中。

forecastWeatherDataTemplate.SetBinding(TextCell.TextProperty, new Binding("mainData.Temperature", BindingMode.Default, new StringToFormattedTempConverter(), null));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM