如何解决无法在ListView中绑定属性
我正在编写天气预报应用程序,无法在ListView中绑定对象的属性。
集合由WeatherModel对象组成,它们具有字符串属性“ Temperature”
Xaml可以看到该集合并将其输出,但是找不到对象属性“温度”。
如何绑定属性“温度”?
这是我的XAML
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
x:Class="IMAP.View.Weather"
xmlns:local="clr-namespace:IMap.viewmodel;assembly=IMAP">
<ContentPage.Resources>
<local:ForecastWeatherviewmodel x:Key="vm"/>
</ContentPage.Resources>
<ContentPage.Content>
<ListView ItemsSource="{Binding items,Source={StaticResource vm}}">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Orientation="Horizontal" Padding="2,15">
<Label Text="{Binding Temperature}"/>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</ContentPage.Content>
</ContentPage>
这是我的viewmodel
namespace IMap.viewmodel
{
public class ForecastWeatherviewmodel : viewmodel
{
public ObservableCollection<WeatherModel> WeatherList { get; set; }
public ObservableCollection<WeatherModel> items
{
get
{
return WeatherList;
}
}
public ForecastWeatherviewmodel()
{
WeatherList = new ObservableCollection<WeatherModel>();
WeatherList.Add(new WeatherModel()
{
Temperature = SomeTemp
});
WeatherList.Add(new WeatherModel()
{
Temperature = SomeTemp
});
OnPropertyChange();
}
}
}
这是我的模特
namespace IMAP.Model
{
public class WeatherModel
{
public string Temperature;
}
}
解决方法
首先,您不能绑定到字段,而应使用属性代替。
public class WeatherModel
{
public string Temperature { get; set; }
}
然后,您可以在视图模型中修复集合管理。同样具有以下命名规则:财产用大写字母,领域用小写字母。现在,您具有同一个集合的两个公共属性,让我们制作一个。
public class ForecastWeatherViewModel : ViewModel
{
// backing field,never interact with it outside of the property getter/setter
private ObservableCollection<WeatherModel> items;
// public property,bind here,interact with it
public ObservableCollection<WeatherModel> Items
{
get => items; // same as "get { return items; }" but shorter
set
{
items = value;
OnPropertyChange();
}
}
public ForecastWeatherViewModel()
{
Items = new ObservableCollection<WeatherModel>();
Items.Add(new WeatherModel()
{
Temperature = SomeTemp
});
Items.Add(new WeatherModel()
{
Temperature = SomeTemp
});
}
}
<ListView ItemsSource="{Binding Items,Source={StaticResource vm}}">
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。