gpt4 book ai didi

xaml - 将属性绑定(bind)到 Listview DataTemplate 中的元素

转载 作者:行者123 更新时间:2023-12-02 06:30:16 27 4
gpt4 key购买 nike

我无法在 Xamarin 表单的 DataTemplate 中进行数据绑定(bind)。我可以让它与 ListView 一起工作(即绑定(bind) RowHeight),但是一旦在 DataTemplate 中,将事情设置为我的属性ViewModel 没有影响。

在下面的示例中,如果我将 ColumnDefinition.Width 设置为一个属性,它会被完全忽略,但将其设置为硬值也能正常工作。我已经放入一个标签以查看属性值是什么,当它在 Datatemplate 中时它变成空白,并且我已经重新检查该属性是否正确,因为如果我将标签从Listview,它显示正确的值。

有什么想法吗?

更新:

我的类是“ParentPage”,它有两个属性:“Patients”和“Settings”。患者有一个可观察的“PatientList”集合,我将如何绑定(bind)到标签下面显示的“Settings.Fontsize”。我已经尝试了所有我能想到的组合:

<ListView   x:Name="listView" ItemsSource="{Binding ParentPage.Patients.PatientsList}" RowHeight="{Binding ParentPage.Settings.RowHeight}"  >
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Grid HorizontalOptions="FillAndExpand">
<Grid.RowDefinitions>
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Image Grid.Row="0" Grid.Column="0"
Source="{Binding Picture}" />

<Label TextColor="Red" Text="{Binding ParentPage.Settings.FontSize}"
HorizontalOptions="Center" />

</Grid>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>

最佳答案

BindingContext,换句话说,listview 的“ItemsSource”,适用于整个 listview,包括 DataTemplate。所以,如果你想绑定(bind)一些东西,那么它的属性应该在 BindingContext 中,在你的情况下它是 Patients。所以,Pasient 类应该包含这个属性。但是,有一个技巧。如果你想绑定(bind)一些不在 ListView 绑定(bind)上下文中的东西,那么你应该命名你的 ListView ,比如 x:Name = "YourListView"然后在你的数据模板中为你的绑定(bind)写这个:

Property="{Binding Source={x:Reference Name = "YourListView"},
Path=BindingContext.YourNameOfPropertyInViewModel}"

有了这个,您的属性将使用您的 ListView 元素级别的绑定(bind)上下文,在您的情况下是 ViewModel。

关于xaml - 将属性绑定(bind)到 Listview DataTemplate 中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40088645/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com