【问题标题】:How to do the equivalent of {Binding Source} in code?如何在代码中做相当于 {Binding Source} 的事情?
【发布时间】:2025-11-25 09:30:01
【问题描述】:

我正在扩展一个控件,以便能够在我当前的 Xamarin 项目中重用它。作为此控件的一部分,我需要以编程方式创建一个 DataTemplate。我已经弄清楚了这部分,它工作正常。

DataTemplate 中有一个标签。我需要将 Label 的 BindingContext 属性绑定到{Binding Source}。我需要将 Label 的 Text 属性绑定到 {Binding Path=Name}

这适用于 XAML,但我不想将其复制到代码库中的一百万个不同位置。

<dxGrid:TemplateColumn FieldName="MyPropertyName"
                    Caption="MyColumn">
<dxGrid:TemplateColumn.DisplayTemplate>
    <DataTemplate>
        <Label BindingContext="{Binding Source}"
                Text="{Binding Source, Path=MyPropertyName}" />
    </DataTemplate>
</dxGrid:TemplateColumn.DisplayTemplate>

我的扩展控件现在看起来像这样:

public class MyColumn : TemplateColumn
{
    public MyColumn()
    {
        DataTemplate displayTemplate = new DataTemplate(() =>
        {
            BindingBase textBinding = new Binding(FieldName);

            Label label = new Label();

            // TODO: Bind BindingContextProperty to {Binding Source}
            //label.SetBinding(BindingContextProperty, binding);

            label.SetBinding(Label.TextProperty, textBinding);
            return new ViewCell
            {
                View = label
            };
        });

        DisplayTemplate = displayTemplate;
    }
}

我正在绑定绑定,因为我不确定如何在代码中执行与 {Binding Source} 等效的操作。任何帮助将不胜感激。

【问题讨论】:

    标签: xaml xamarin.forms


    【解决方案1】:

    @Eugene - 感谢您的回复。不幸的是,这不起作用,并且像这样绑定到“源”会引发空引用异常。今天早上我又通过了它,让它以这种方式工作:

    public MyColumn()
    {
        DataTemplate displayTemplate = new DataTemplate(() =>
        {
            Grid grid = new Grid();
            grid.SetBinding(Grid.BindingContextProperty, "Source");
    
            Label label = new Label();
            label.SetBinding(Label.TextProperty,FieldName);
    
            grid.Children.Add(label);
    
            return grid;
        });
    
        this.DisplayTemplate = displayTemplate;
    }
    

    【讨论】:

      【解决方案2】:

      很简单,使用属性名

      label.SetBinding(BindingContextProperty, "Source");
      

      【讨论】:

      • 如果有人想知道为什么这个简单的答案不起作用,Eugene cmets 在看到 OP 之后如何让它工作之后,在the equivalent Xamarin Forums thread 中他错过了这是在 DataTemplate 中。跨度>
      最近更新 更多