【发布时间】: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