首页 > 解决方案 > 如何为 Xamarin 中的绑定设置空路径?

问题描述

我有一个绑定,我不需要路径。如果我在 xaml 中设置 ItemTemplate 效果很好。

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage
    x:Class="TestBindingPath.MainPage"
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml">
    <ListView x:Name="listview1" ItemsSource="{Binding Students}">
        <ListView.ItemTemplate>
            <DataTemplate>
                <ViewCell>
                    <Label Text="{Binding}" />
                </ViewCell>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</ContentPage>

但是如果我在代码中设置 ItemTemplate 它会引发异常

listview1.ItemTemplate = new DataTemplate(() => {
    Label label = new Label();
    label.SetBinding(Label.TextProperty, new Binding());
    return (new ViewCell() {
        View = label
    });
});

在此处输入图像描述 那么如何为代码中的绑定设置一个空路径?

标签: xamarinbinding

解决方案


这是绑定方法结构。

 public Binding(string path, BindingMode mode = BindingMode.Default, IValueConverter converter = null, object converterParameter = null, string stringFormat = null, object source = null);

尝试这样做。

    listview1.ItemTemplate = new DataTemplate(() => {
    Label label = new Label();
    label.SetBinding(Label.TextProperty, new Binding(source:Students));
    return (new ViewCell() {
        View = label
    });
});

学生属性必须在代码 bihind cs 中


推荐阅读