【问题标题】:Binding on the View - how to get the details of parent property from a child list绑定视图 - 如何从子列表中获取父属性的详细信息
【发布时间】:2021-10-18 04:36:36
【问题描述】:

我正在使用 Xamarin 表单。

我有一个包含几个列表视图的简单视图。整个视图有一个带有视图模型的 BindingContext。视图模型类包含一个 BackgroundColor。 问题:如何从列表视图的 dataTemplate 中访问 BackgroundColor 属性。

ViewModel.cs

public class TestViewModel {
 public System.Drawing.Color BackgroundColor { get; set; }
 public List<Employee> Employees { get; set; }
}

上述类的一个实例为视图设置了一个BindingContext 查看.xaml

<ContextPage.... >
....
 <listview  ItemsSource="{Binding Employees}"...
  <DataTemplate>
    <Grid BackgroundColor="{Binding BackgroundColor}">

</ContentPage>

上述网格的背景不起作用,因为当前上下文现在位于 Employee 集合中。那么如何在列表视图中访问视图模型中的“BackgroundColor”。

【问题讨论】:

    标签: c# xaml xamarin.forms binding


    【解决方案1】:

    Xamarin 中 Grid 控件的BackgroundColor 具有 Xamarin.Forms.Color 类型,但没有 System.Drawing.Color,因此您必须在类中更改类型。

    public class TestViewModel {
     public Xamarin.Forms.Color BackgroundColor { get; set; }
     public List<Employee> Employees { get; set; }
    }
    

    更新:

    您可以使用 RelativeSource FindAncestor 从 TestViewModel 实例中获取所需的属性。

    这里例如:https://stackoverflow.com/a/63713316/1979354

    【讨论】:

    • 同意,但是当我在列表视图数据模板中时如何映射该属性? .... = 除非我在存储背景颜色的员工类本身
    • @Peter,我已经更新了答案,当您在模板中时,您需要相对来源才能从父上下文中获取价值。
    • 我不得不从那里调整几件事,也许您可​​以将其添加到您的答案中 {Binding BackgroundColor, Source={RelativeSource AncestorType={x:Type ContentPage}, Mode=FindAncestor}}应该是 Source={RelativeSource.. in Xamarin RelativeSource={RelativeSource AncestorType = 不起作用并且抱怨 RelativeSource 不在 BindingExtension 中 感谢伙伴获取该链接。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-06
    • 2023-04-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多