Reputation: 2531
I'm creating weather app with forecast. I have created ListView
with TextCell
as entries.
I want to format test inside cell to XXX YY where:
I have observable collection declared in ContentPage
and it is my ItemSource
, I have another important property, 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. Temperature is double and weather unit have Extension that return String. Right now, only Temperature value is shown properly and date as detail:
Upvotes: 0
Views: 700
Reputation: 2256
I also like David's approach. Having a get-only property in your JSON class is nothing to worry about. 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));
Upvotes: 0
Reputation: 13620
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 ");
Upvotes: 1