You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Xamarin Forms的XAML页面中引用指定控件为自定义控件属性赋值?

问题:如何在XAML中将自定义控件的属性绑定到页面内的其他控件?

我有一个自定义控件BlurredImage,它包含一个VisualElement类型的属性RootElement。我希望在XAML中将该属性设置为当前XAML页面内x:Name为myStackLayout的StackLayout控件。

自定义控件代码

public class BlurredImage : Image
{
    public static readonly BindableProperty RootElementProperty = BindableProperty.Create(nameof(RootElement), typeof(VisualElement), typeof(BlurredImage), propertyChanged: RootElementPropertyChanged);
    public VisualElement RootElement { get => (VisualElement)GetValue(RootElementProperty); set => SetValue(RootElementProperty, value); }

    static void RootElementPropertyChanged(BindableObject bindable, object oldValue, object newValue)
    {
        // Do some process
    }
}

我原来的XAML代码

<StackLayout x:Name="myStackLayout">
   ...
</StackLayout>

<controls:BlurredImage RootElement="{Binding myStackLayout, Source={x:Reference thisPage}}" />

解决方案

直接使用x:Reference引用目标控件即可,无需通过Binding,因为我们要的是直接赋值控件实例:

<StackLayout x:Name="myStackLayout">
   ...
</StackLayout>

<controls:BlurredImage RootElement="{x:Reference myStackLayout}" />

说明

  • {x:Reference}可以直接引用XAML中通过x:Name命名的控件实例,正好匹配RootElement的VisualElement类型要求,能直接完成赋值。
  • 你原先的Binding写法属于冗余操作,因为myStackLayout是页面的直接控件实例,而非绑定上下文(ViewModel)中的属性,直接引用更简洁可靠。

另外你的自定义控件代码没有问题,RootElement的可绑定属性定义正确,属性变更回调会在赋值后正常触发。

内容的提问来源于stack exchange,提问作者Junaid Pathan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 01:01:11