XamarinForm DataTemplate ListView绑定

时间:2018-02-11 21:49:48

标签: data-binding xamarin.forms custom-controls datatemplate

我想绑定到ListView DataTemplate

中引用的CustomControl内的变量

情况如下: 我有一个包含带有许多DataTemplates的ListView的自定义控件来显示各种ViewCell(它基本上是一组必须根据其“类型”显示的动态字段)。

<?xml version="1.0" encoding="UTF-8"?>
<ContentView xmlns="http://xamarin.com/schemas/2014/forms" 
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         xmlns:s4gvForms="clr-namespace:S4GVMobile.Forms;assembly=S4GVMobile"
         xmlns:s4gvControls="clr-namespace:S4GVMobile.Controls;assembly=S4GVMobile"
         x:Class="S4GVMobile.Controls.AttributesList"
         x:Name="S4GVAttributesListControl"
         >
<ContentView.Resources>
    <ResourceDictionary>
        <!-- MANY DATA TEMPLATES HERE, ONLY ONE LEFT FOR REFERENCE -->
        <DataTemplate x:Key="s4gvAttributePictureTemplate">
            <ViewCell x:Name="s4gvAttributePictureViewCell">
                <ViewCell.View>
                    <StackLayout Orientation="Vertical">
                        <Label Text="{Binding Attribute.Key}" />
                        <s4gvControls:AttributePicture ParentID="{Binding Source={x:Reference s4gvAttributePictureViewCell}, Path=Parent.BindingContext.EntityID}" AttributeValue="{Binding .}"  />
                    </StackLayout>
                </ViewCell.View>
            </ViewCell>
        </DataTemplate>
        <!-- ... -->
        <!-- AGAIN, LONG LIST IN THE SELECTOR -->
        <s4gvForms:AttributeDataTemplateSelector x:Key="s4gvAttributeDataTemplateSelector"
                                                 AttributePictureTemplate="{StaticResource s4gvAttributePictureTemplate}"
                                                 />
    </ResourceDictionary>
</ContentView.Resources>
<StackLayout>
    <ListView x:Name="s4gvAttributes" HasUnevenRows="True" ItemTemplate="{StaticResource s4gvAttributeDataTemplateSelector}" ItemsSource="{Binding AttributeValues}" />
</StackLayout>

我将这个项目列表(ListView所需)和另一个EntityID传递给此自定义控件。

<s4gv:AttributesList x:Name="s4gvSerialAttributes" AttributeValues="{Binding Serial.AttributeValues}" EntityID="{Binding Serial.SerialID}" VerticalOptions="FillAndExpand"/>

自定义控件具有所需的可绑定属性(AttibuteValues和EntityID)并依赖于专用的ViewModel

我需要从DataTemplate中检索EntityID(并将其放在ParentID属性中);此值位于自定义控件的ViewModel中,但它位于ListView的DataTemplates“外部”。我已经尝试过使用Parent.BindingContext(它适用于Command和CommandParameter),但它似乎只能进入ListView的上下文而不是更高,尽管我需要进一步向上移动到CustomControl本身。

<s4gvControls:AttributePicture ParentID="{Binding Source={x:Reference s4gvAttributePictureViewCell}, Path=Parent.BindingContext.EntityID}" AttributeValue="{Binding .}"  />

有什么想法吗?如果需要,我很乐意重组整个事情。

0 个答案:

没有答案