【问题标题】:binding a Custom control in DataTemplate在 DataTemplate 中绑定自定义控件
【发布时间】:2014-10-07 16:06:46
【问题描述】:

一段时间以来,我一直在解决有关 XAML 中数据绑定的问题。

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:Pedagouge.Views;assembly=Pedagouge"
             x:Class="Pedagouge.Views.StudentGroupView">
  <StackLayout>
    <ListView x:Name="Students">
      <ListView.ItemTemplate>
        <DataTemplate>
          <ViewCell>
            <StackLayout Orientation="Horizontal">
              <local:PhotoView x:Name="Photo" Persona="{Binding}" />
              <StackLayout Orientation="Vertical" HorizontalOptions="StartAndExpand" VerticalOptions="StartAndExpand">
                <Label Text="{Binding FullName}" />
                <Label Text="{Binding StudentIsAt.Group.Name}" />
              </StackLayout>
            </StackLayout>
          </ViewCell>
        </DataTemplate>
      </ListView.ItemTemplate>
    </ListView>
  </StackLayout>
</ContentPage>

我以为我已经想到了绑定,但我遇到的问题清楚地表明我没有。 无论如何,问题在于对于自定义控件PhotoView,似乎{Binding} 使用的属性Persona 的绑定上下文是PhotoViewBindingContext,而不是DataTemplate 的上下文,就像Labels 向下几行一样。

如果这是 WPF,我会直接将绑定更改为

Persona="{Binding DataContext,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=ListBoxItem}}"

这可能会修复它,但在这里不起作用(RelativeSource 显然没有定义)。

怎么会?我怎样才能让Persona 绑定到DataTemplates 上下文,就像Labels 的情况一样?

【问题讨论】:

  • 如果在视图模型上添加属性Self { get { return this; } },然后将 PhotoView.Persona 上的绑定更改为{Binding Self},会怎样?另外..看看这个:stackoverflow.com/questions/22595388/…
  • @mrtig 听起来这仍然会给我一个对视图模型的引用,而不是当前绑定到 DataTemplate 的项目
  • 是的,我想你是对的。您可以尝试绑定集合的每个成员的“self”属性。 ..或者您可以尝试ElementName 建议(在上面的链接中)。
  • ElementName 解决方案只生成NullPointerException。我确实首先将整个 ViewCell 移到了它自己的控件中。

标签: xamarin.forms


【解决方案1】:

Xamarin.Forms(最高 1.2.x)绑定始终使用 BindableObject.BindingContext 作为上下文绑定。

在模板项目的情况下,项目上下文设置为模板元素,在这种情况下为ViewCell,并递归设置为ViewCell.ViewStackLayout您的PhotoView,内部StackLayout 和 2 Labels。

FullNameStudentIsAt.Group.Name 有效这一事实是一个强有力的暗示。

所以,当你说

[...] for the custom control PhotoView it seems that the binding context used by 
{Binding} to the property Persona is the PhotoView's BindingContext, not the 
DataTemplate's context, [...]

既对又错。

{Binding}使用的绑定上下文是PhotoView的Bindingcontext,也是DataTemplate的上下文。

如果绑定没有按预期工作,可能是因为PhotoView 以某种方式将BindingContext 设置为this,并阻止{Binding} 按预期工作,但我不能说没有看到@ 987654336@的代码。

【讨论】:

  • PhotoView 确实设置了BindingContext,但设置为ViewModel 类。从那以后,我删除了那个 ViewModel,然后它一切都按我的预期工作了(即,就像它对 Labels 绑定所做的那样)。
  • 如果您对答案没问题,请接受。它可能会帮助其他人
猜你喜欢
  • 2016-03-11
  • 2015-03-06
  • 2012-12-12
  • 1970-01-01
  • 2013-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-11
  • 2011-05-21
相关资源
最近更新 更多