簡體   English   中英

在ControlTemplate中綁定ListView

[英]Bind ListView in ControlTemplate

我的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}”。

我們需要有關您的代碼的更多詳細信息以及您創建控件模板的意圖,但以下步驟可以幫助您:

1-首先:ControlTemplate實用程序,

在Xamarin Forms中,'ControlTemplate'用於自定義控件的外觀。 更確切地說,它定義了顯示內容的布局。

  • 所以它應該包含一個'ContentPresenter'對象。
  • 它只能應用於'ContentPage'和'ContentView'對象

- >你想在哪個UI'Element'上綁定你的ControlTemplate?

2-然后使用TemplateBindings(我懷疑這里有問題)

如果我是對的,TemplateBindings只能用於綁定到' Parent'Bindable Properties

當你這樣做時:

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

沒關系,因為'BindingContext'是一個BindableProperty,但如果你這樣做:

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

這是因為'BindingContext.MyItems'不是BindableProperty(我推測)

3-最后,該怎么辦?

解決方案1

在擁有模板化控件的頁面中創建,綁定到ViewModel的中間BindableProperties

然后你的'TemplateBindings'應該引用這些屬性。

這里使用'TemplateBinding'和'BindableProperty'的一個很好的例子: Xamarin TemplateBinding文檔

解決方案2

對我來說,我更願意提取到App.xaml,

  • 將ListView DataTemplate轉換為新的數據模板資源

  • 將Listview屬性轉換為新的'ListView'樣式

在我的頁面中我會:

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

實際上,您可以直接在Style中包含'DataTemplate'屬性...

如果有幫助,請告訴我。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM