C# 无法在ListView中绑定属性
我正在写一个天气预报应用程序,我不能绑定ListView中对象的属性 集合由WeatherModel对象组成,这些对象具有字符串属性“Temperature” Xaml看到集合并将其输出,但找不到对象属性“温度” 如何绑定属性“温度” 这是我的XAMLC# 无法在ListView中绑定属性,c#,visual-studio,xaml,xamarin,xamarin.forms,C#,Visual Studio,Xaml,Xamarin,Xamarin.forms,我正在写一个天气预报应用程序,我不能绑定ListView中对象的属性 集合由WeatherModel对象组成,这些对象具有字符串属性“Temperature” Xaml看到集合并将其输出,但找不到对象属性“温度” 如何绑定属性“温度” 这是我的XAML <?xml version="1.0" encoding="utf-8" ?> <ContentPage xmlns="http://xamarin.com/schemas/20
<?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>
首先,不能绑定到字段,而是使用属性
公共类天气模型
{
公共字符串温度{get;set;}
}
然后,您可以修复视图模型中的集合管理。还有以下命名规则:属性用大写字母,字段用小写字母。现在,同一个集合有两个公共属性,让我们创建一个公共属性
公共类预测WeatherViewModel:ViewModel
{
//backing字段,永远不要在属性getter/setter之外与其交互
私人可观测收集项目;
//公共财产,绑定在这里,与之互动
公共可观测收集项目
{
get=>items;//与“get{return items;}”相同,但更短
设置
{
项目=价值;
OnPropertyChange();
}
}
公共预测天气视图模型()
{
Items=新的ObservableCollection();
添加项目(新天气模型()
{
温度=某个温度
});
添加项目(新天气模型()
{
温度=某个温度
});
}
}
首先,您不能绑定到字段,请使用属性来实现此目的
公共类天气模型
{
公共字符串温度{get;set;}
}
然后,您可以修复视图模型中的集合管理。还有以下命名规则:属性用大写字母,字段用小写字母。现在,同一个集合有两个公共属性,让我们创建一个公共属性
公共类预测WeatherViewModel:ViewModel
{
//backing字段,永远不要在属性getter/setter之外与其交互
私人可观测收集项目;
//公共财产,绑定在这里,与之互动
公共可观测收集项目
{
get=>items;//与“get{return items;}”相同,但更短
设置
{
项目=价值;
OnPropertyChange();
}
}
公共预测天气视图模型()
{
Items=新的ObservableCollection();
添加项目(新天气模型()
{
温度=某个温度
});
添加项目(新天气模型()
{
温度=某个温度
});
}
}
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;
}
}