如何解决Xamarin 将字符串数组绑定到 BindableLayout 仅在 Xaml 热重载后有效
我在将 string[] 的值绑定到 BindableLayout 的 DataTemplate 时遇到问题。我在 Shell 弹出模板的 AboutPage 中重新创建了该问题。
关于Page.xaml
<ContentPage.BindingContext>
<vm:Aboutviewmodel />
</ContentPage.BindingContext>
<StackLayout VerticalOptions="Center"
Padding="20"
BindableLayout.ItemsSource="{Binding Data}">
<BindableLayout.ItemTemplate>
<DataTemplate>
<Label FontSize="Large"
Text="{Binding .}"
BackgroundColor="PowderBlue"/>
</DataTemplate>
</BindableLayout.ItemTemplate>
</StackLayout>
关于viewmodel.cs
namespace App2.viewmodels
{
public class Aboutviewmodel : Baseviewmodel
{
private string[] _data;
public string[] Data
{
get
{
return _data;
}
set
{
if (_data != value)
{
_data = value;
OnPropertyChanged();
}
}
}
public Aboutviewmodel()
{
Title = "About";
Data = new string[] { "One","Two","Three" };
}
}
}
首次打开页面时,标签数量正确,但没有任何文本。 如果我编辑 Text="{Binding .}" 绑定在 Xaml 热重载后工作。 为什么在字符串显然不是空的或 null 的情况下,字符串一开始就不显示?
解决方法
我以一种意想不到的方式解决了这个问题。只需将 DataTemplate 移动到它自己的文件中,这个问题就会消失。有人可以向我解释为什么这有效吗?我的新代码并排生成两个 StackLayouts,绑定到相同的数据,但只绑定到右侧的 Stackview,其 DataTemplate 在其他地方定义为 ListItemView.xaml 在应用程序运行时显示数据。左边的 StackView 一开始是空的 Labels,然后我从 Text="{Binding .}"
中删除句号 (.) 并替换它后,Xaml Hot Reload 运行并显示字符串。
ListItemView.xaml
<DataTemplate xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="App2.Views.ListItemView">
<Label FontSize="Large"
Text="{Binding .,Mode=OneWay}"
BackgroundColor="PowderBlue"/>
</DataTemplate>
关于Page.xaml
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="App2.Views.AboutPage"
xmlns:vm="clr-namespace:App2.ViewModels"
xmlns:views="clr-namespace:App2.Views"
Title="{Binding Title}"
x:DataType="vm:AboutViewModel">
<ContentPage.BindingContext>
<vm:AboutViewModel />
</ContentPage.BindingContext>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1*"/>
<ColumnDefinition Width="1*"/>
</Grid.ColumnDefinitions>
<StackLayout VerticalOptions="Center"
Padding="20"
BindableLayout.ItemsSource="{Binding Data}"
Grid.Column="0">
<BindableLayout.ItemTemplate>
<DataTemplate>
<Label FontSize="Large"
Text="{Binding .,Mode=OneWay}"
BackgroundColor="PowderBlue"/>
</DataTemplate>
</BindableLayout.ItemTemplate>
</StackLayout>
<StackLayout VerticalOptions="Center"
Padding="20"
BindableLayout.ItemsSource="{Binding Data}"
Grid.Column="1">
<BindableLayout.ItemTemplate>
<views:ListItemView />
</BindableLayout.ItemTemplate>
</StackLayout>
</Grid>
</ContentPage>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。