【发布时间】:2019-07-13 15:13:20
【问题描述】:
我还在学习中,请多多包涵。
我正在尝试在我的 Xamarin.Form 中显示 ListView。到目前为止,这就是我所拥有的,并且效果很好:
<?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:maps="clr-namespace:Xamarin.Forms.Maps;assembly=Xamarin.Forms.Maps"
xmlns:local="clr-namespace:GasStations"
x:Class="GasStations.MainPage">
<StackLayout>
<ListView x:Name="ListView_Pets">
</ListView>
</StackLayout>
</ContentPage>
这是代码隐藏:
var obj = JsonConvert.DeserializeObject(coord);
List<String> storeList = new List<String>();
string store = string.Empty;
foreach (var item in ((JArray)obj))
{
store = item.Value<string>("name");
//desc = item.Value<string>("description"); /* This is the string I want to display */
storeList.Add(store);
}
ListView_Pets.ItemsSource = storeList;
它可以工作,并在ListView 中显示商店名称。你可以看到screenshot here。
现在,除了在ListView 中显示商店Name,我还想显示描述(和任何其他值)。我假设每行都需要Labels,类似于asp.netGridViewItemTemplate。
我尝试了类似的方法,但没有成功:
<?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:maps="clr-namespace:Xamarin.Forms.Maps;assembly=Xamarin.Forms.Maps"
xmlns:local="clr-namespace:GasStations"
x:Class="GasStations.MainPage">
<StackLayout>
<ListView x:Name="ListView_Pets" ItemsSource="{Binding MyClass}" >
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<ViewCell.View>
<Label x:Name="Label_Name" Text="Name" />
<Label x:Name="Label_Desc" Text="Description" />
</ViewCell.View>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
</ContentPage>
我可以访问代码隐藏中的Name 和Description(使用desc = item.Value<string>("description");,但我不知道如何将这些值绑定到表单中的标签。
【问题讨论】:
-
你没有使用 MVVM 范式的优势。如答案所示,指定新添加的标签所需的绑定。 x:name 破坏了 MVVM 模式,所以尽量远离它
-
stackoverflow.com/a/54280876/5772095 ... 为您解决。
-
“但它没有构建” - 你得到什么构建错误?
-
@Jason,他的
xaml有两次ViewCell,我没有注意到。
标签: c# xamarin xamarin.forms visual-studio-2017 xamarin.forms.listview