Xamarin.Forms编译的绑定不适用于DataTemplate

问题描述:

我遇到在DataTemplate中使用编译的绑定

我添加了 XamlComilation App.xaml.cs

// https://docs.microsoft.com/en-us/xamarin/xamarin-forms/xaml/xamlc
[assembly: XamlCompilation(XamlCompilationOptions.Compile)]
namespace Solution.Project

然后我将 DataTemplate 更改为

<DataTemplate x:Key="RectLayerDataTemplate" x:DataType="{x:Type viewmodels:RectLayerViewModel}">
    <forms:RectLayerView forms:ValueX="{Binding ValueX}"
                         forms:ValueY="{Binding ValueY}"
                         forms:ValueWidth="{Binding ValueWidth}"
                         forms:ValueHeight="{Binding ValueHeight}"
                         forms:Color="{Binding Color}" />
</DataTemplate>

但是, DataTemplate 不适用于 BindableLayout.ItemSource

<AbsoluteLayout x:Name="CanvasLayout"
                BindableLayout.ItemsSource="{Binding LayerViewModels}" />


您是否使用了 AbsoluteLayout 来使布局重叠,所以您认为它不起作用?

Did you use AbsoluteLayout to make the layout overlap, so you think it didn't work?

我使用 DataTemplate $创建了一个简单的示例c $ c>并将其设置为 StackLayout BindableLayout ,效果很好。

I create a simple sample,with the DataTemplate and set it to the StackLayout BindableLayout,it works well.

page.xaml:

the page.xaml:

<StackLayout x:Name="CanvasLayout" Orientation="Vertical"
             BindableLayout.ItemsSource="{Binding LayerViewModels}" />

page.xam.cs:

page.xam.cs:

public MyPage()
    {
        InitializeComponent();
        BindingContext = new MyData();          
        LayerDataTemplate s = new LayerDataTemplate();
        BindableLayout.SetItemTemplate(CanvasLayout, s.template);
    }

我的数据

public class MyData
{

    public ObservableCollection<RectLayerViewModel> LayerViewModels { set; get; } = new ObservableCollection<RectLayerViewModel>();

    public MyData()
    {
        for (var x = 0; x < 6; x++)
        {
            LayerViewModels.Add(new RectLayerViewModel { Name = $"Added at {LayerViewModels.Count}", Type = 1 });
        }
    }
}

RectLayerViewModel

public class RectLayerViewModel
{
    public string Name { get; set; }
    public int Type { get; set; }
}

DataTemplate

<?xml version="1.0" encoding="UTF-8"?>
<ResourceDictionary  xmlns="http://xamarin.com/schemas/2014/forms" 
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"     
         xmlns:local ="clr-namespace:EntryCa"
         x:Class="EntryCa.LayerDataTemplate">
<DataTemplate x:Key="RectLayerDataTemplate" x:DataType="local:RectLayerViewModel">

         <Label Text="{Binding Name}"
                   TextColor="Red"
                   FontAttributes="Bold" />
  
</DataTemplate>