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

Xamarin Forms自定义控件TextChanged事件绑定失败问题求助

问题原因

你在自定义控件TitleAndEntry中定义的可绑定属性是TextEntryChanged,但在页面XAML里却试图绑定TextChanged——这个名称在你的控件中既没有对应的事件,也没有对应的可绑定属性,导致系统找不到匹配项,抛出报错。

解决方案

方案一:修正现有代码的使用方式

直接修改页面XAML中的属性名,匹配控件里定义的TextEntryChanged:

<ctrl:TitleAndEntry
    x:Name="user"
    Margin="{StaticResource NormalTopPadding}"
    TextLabel="{x:Static local:AppResources.User}"
    TextEntryChanged="OnMyTextChanged"/>

修改后就能正确绑定你定义的可绑定属性,事件处理器会被附加到内部的myEntry控件上。

方案二:改用自定义事件(推荐)

这种方式更符合Xamarin.Forms的控件设计规范,直接在自定义控件中声明TextChanged事件,转发内部控件的事件:

  1. 替换控件后台代码中TextEntryChanged相关逻辑:
public partial class TitleAndEntry : ContentView
{
    public TitleAndEntry()
    {
        InitializeComponent();
        // 绑定内部控件事件到自定义事件
        myEntry.TextChanged += MyEntry_TextChanged;
    }

    // 声明自定义TextChanged事件
    public event EventHandler<TextChangedEventArgs> TextChanged;

    private void MyEntry_TextChanged(object sender, TextChangedEventArgs e)
    {
        // 传递内部控件的事件到外部
        TextChanged?.Invoke(this, e);
    }

    // 保留其他已实现的BindableProperties...
}
  1. 页面XAML保持原有写法即可:
<ctrl:TitleAndEntry
    x:Name="user"
    Margin="{StaticResource NormalTopPadding}"
    TextLabel="{x:Static local:AppResources.User}"
    TextChanged="OnMyTextChanged"/>

额外检查

确保页面XAML顶部已正确引用自定义控件的命名空间,比如:

xmlns:ctrl="clr-namespace:Test.Controls"

内容的提问来源于stack exchange,提问作者Fred Fickleberry III

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 08:56:09