【问题标题】:Bind ListView in ControlTemplate在 ControlTemplate 中绑定 ListView
【发布时间】:2017-10-29 22:52:50
【问题描述】:

我的 App.xaml 中有一个 ControlTemplate,如下所示:

<ControlTemplate x:Key="MyTempplate">
    <ListView x:Name="MyListView"
        AutomationId="SelectRelationListViewId"
        ItemsSource="{Binding MyListViewData}" 
        SelectedItem="{Binding MySelectedItem}"
        BackgroundColor="White" 
        RowHeight="60" 
        SeparatorColor="White" 
        IsGroupingEnabled="False" 
        VerticalOptions="FillAndExpand">
        <ListView.ItemTemplate>
            <DataTemplate>
                <ViewCell>
                    <Grid BackgroundColor="#E7E4E0" 
                          Padding="20,0,20,0">
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="Auto"/>
                        </Grid.ColumnDefinitions>
                            <Label Grid.Column="0" 
                                   Text="{Binding MyName}" 
                                   VerticalOptions="CenterAndExpand"/>
                    </Grid>
                </ViewCell>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</ControlTemplate>

我的页面与我的 ViewModel 绑定,如果我将模板中的代码复制/粘贴到我的 pagem,数据和事件会得到正确处理,但当我尝试使用我的模板时没有任何反应,ListView 为空且事件为没有触发。

我已经尝试过“{TemplateBinding DataContext.MyPropertyNameToBind}”。

【问题讨论】:

  • 感谢您的提示,但它也不起作用
  • 如果是Xamarin.Forms,你应该使用{TemplateBinding BindingContext.MyPropertyNameToBind} 而不是DataContext

标签: c# listview binding xamarin.forms controltemplate


【解决方案1】:

我们需要有关您的代码和您创建控件模板的意图的更多详细信息,但以下步骤可以帮助您:

1- 首先:ControlTemplate 实用程序,

在 Xamarin Forms 中,“ControlTemplate”用于自定义控件的外观。更准确地说,它定义了显示内容的布局。

  • 所以它应该包含一个“ContentPresenter”对象。
  • 只能应用于“ContentPage”和“ContentView”对象

--> 您尝试将 ControlTemplate 绑定到哪个 UI“元素”?

2- 然后使用 TemplateBindings(我怀疑这里有问题)

如果我是对的,TemplateBindings 只能用于绑定到“父级”可绑定属性

当你在做的时候:

<ControlTemplate x:Key="MyTemplate">
   <ListView ItemsSource={TemplateBinding BindingContext} />
...

没关系因为'BindingContext'是一个BindableProperty,但如果你这样做:

<ControlTemplate x:Key="MyTemplate">
   <ListView ItemsSource={TemplateBinding BindingContext.MyItems} />
...

这是 ko 因为 'BindingContext.MyItems' 不是 BindableProperty(我想)

3- 最后,怎么办?

解决方案 1

在拥有模板化控件的页面中创建,中间BindableProperties绑定到您的 ViewModel。

那么您的“TemplateBindings”应该引用这些属性。

在这里使用“TemplateBinding”和“BindableProperty”的一个很好的例子: Xamarin TemplateBinding documentation.

解决方案 2

对我来说,我更喜欢解压到 App.xaml,

  • ListView DataTemplate 到一个新的数据模板资源

  • 将 Listview 属性转换为新的“ListView”样式

在我的页面中我会有:

<Page ...>
   <ListView x:Name="myList"
         Style="{StaticResource MyListViewStyle}"
         ItemsSource="{Binding vmItems}"
         DataTemplate="{StaticResource MyListViewDataTemplate}"
         />

事实上,您可以直接在样式中包含“DataTemplate”属性...

如果有帮助,请告诉我。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-14
    • 1970-01-01
    • 2013-02-23
    • 2018-11-08
    • 2015-11-17
    • 2010-09-18
    • 1970-01-01
    相关资源
    最近更新 更多