Bind properties to elements inside a Listview DataTemplate

空扰寡人 提交于 2021-02-10 06:22:06

问题


I can't get databinding to work within a DataTemplate in Xamarin forms. I can get it to work with the ListView (i.e. binding the RowHeight), but once in the DataTemplate, setting things to a property of my ViewModel has no affect.

In the below example, if I set the ColumnDefinition.Width to a property, it is completely ignored, but setting it to a hard value works fine. I have put in a label to see what the property value is and it turns out blank when inside the Datatemplate, and I have re-checked that the property is correct because if I take the label out of the Listview, it displays the correct value.

Any ideas?

UPDATE:

My Class is "ParentPage" which has 2 properties: "Patients" and "Settings". Patients has an observable collection of "PatientList", How would I bind to the "Settings.Fontsize" shown below in the label. I have tried every combination I can think of:

<ListView   x:Name="listView" ItemsSource="{Binding ParentPage.Patients.PatientsList}" RowHeight="{Binding ParentPage.Settings.RowHeight}"  >
  <ListView.ItemTemplate>
    <DataTemplate>
      <ViewCell>
        <Grid HorizontalOptions="FillAndExpand">
          <Grid.RowDefinitions>
            <RowDefinition Height="*" />
          </Grid.RowDefinitions>
          <Image  Grid.Row="0" Grid.Column="0"
             Source="{Binding Picture}" />

          <Label  TextColor="Red" Text="{Binding ParentPage.Settings.FontSize}"   
       HorizontalOptions="Center" />

        </Grid>     
      </ViewCell>
    </DataTemplate>
  </ListView.ItemTemplate>
</ListView>

回答1:


BindingContext, in other words "ItemsSource" for listview, is appliying to whole listview, include DataTemplate. So, if you wanna bind something, then it property should be in BindingContext, in your case it is Patients. So, Pasient class should include this property. But, there is a trick. Where you want bind something, that is not in listview binding context, then you should name your listview, like x:Name = "YourListView" and then in your datatemplate for your binding write this:

Property="{Binding Source={x:Reference Name = "YourListView"},
          Path=BindingContext.YourNameOfPropertyInViewModel}"

With this, your property will use binding context of your listview element level, that is ViewModel in your case.



来源:https://stackoverflow.com/questions/40088645/bind-properties-to-elements-inside-a-listview-datatemplate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!