简体   繁体   English

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

[英]Xamarin Forms ListView Data Binding with two objects

I'm creating weather app with forecast. 我正在创建天气预报应用程序。 I have created ListView with TextCell as entries. 我已经创建了以TextCell作为条目的ListView I want to format test inside cell to XXX YY where: 我想将单元格内部的测试格式设置为XXX YY ,其中:

  • XXX is value XXX很有价值
  • YY is unit YY为单位

I have observable collection declared in ContentPage and it is my ItemSource , I have another important property, weatherUnit . 我在ContentPage声明了可观察的集合,这是我的ItemSource ,我还有另一个重要的属性weatherUnit

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

I'm creating Data template in constructor and setting everything up: 我正在构造函数中创建数据模板并设置所有内容:

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;
}

How I can add to TextCell.TextProperty binding formatting to be temperature and weatherUnit. 如何将TextCell.TextProperty绑定格式添加为temperature和weatherUnit。 Temperature is double and weather unit have Extension that return String. 温度是两倍,天气单位具有返回String的Extension。 Right now, only Temperature value is shown properly and date as detail: 现在,只有温度值正确显示,并且日期显示为详细信息:

当前状态

You can create a readonly property that concats the values for you and then bind to that 您可以创建一个只读属性,为您合并值,然后将其绑定到该属性。

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

binding 捆绑

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

I also like David's approach. 我也喜欢戴维的方法。 Having a get-only property in your JSON class is nothing to worry about. 无需担心在JSON类中具有仅获取属性。 As you don't want to go that way, you can also write a converter class and add that to your binding. 由于您不想那样做,您还可以编写一个转换器类并将其添加到绑定中。

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();
    }
}

And then add it to the binding like this. 然后将其添加到这样的绑定中。

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