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

如何在Xamarin的MainPage.xaml.cs中获取Entry控件的文本内容?

我太懂这种被Xamarin的各种机制搞得头大的感觉了!别焦虑,给你两个简单直接的方案,不用硬啃晦涩的Binding文档也能快速解决你的问题:

方法1:直接通过控件名称获取(最简单上手)

这种方式完全不需要涉及Binding,适合快速验证你的需求:

  • 第一步,在MainPage.xaml里给你的Entry控件加上x:Name属性,同时可以加个按钮触发获取文本的动作:
<Entry x:Name="MyInputEntry" Placeholder="请输入内容..." />
<Button Text="获取输入文本" Clicked="OnGetTextButtonClicked" Margin="0,10,0,0" />
  • 第二步,在MainPage.xaml.cs里直接通过这个名称访问Entry的Text属性:
private void OnGetTextButtonClicked(object sender, EventArgs e)
{
    // 直接获取Entry的文本内容
    string userInput = MyInputEntry.Text;
    
    // 这里可以添加你自己的逻辑,比如打印内容或者处理数据
    Console.WriteLine($"用户输入的内容是:{userInput}");
}

这个方法的优点是零学习成本,拿来就能用;缺点是如果页面控件变多,代码和UI耦合会比较严重,但对于简单场景完全够用。

方法2:极简版Binding实现(适合稍复杂的后续扩展)

如果之后你的页面逻辑变复杂,直接引用控件会让代码变得混乱,那可以试试这个简化版的Binding,不用深究复杂的MVVM概念,照着抄就能跑:

  1. 先创建一个简单的ViewModel类(可以放在MainPage.xaml.cs文件里,或者单独新建一个文件):
public class MainPageViewModel : INotifyPropertyChanged
{
    private string _userInputText;
    
    // 绑定到Entry的属性
    public string UserInputText
    {
        get => _userInputText;
        set
        {
            _userInputText = value;
            // 通知UI属性值更新
            OnPropertyChanged(nameof(UserInputText));
        }
    }

    // 实现INotifyPropertyChanged接口的必备事件
    public event PropertyChangedEventHandler PropertyChanged;
    
    protected void OnPropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}
  1. 在MainPage.xaml.cs里初始化ViewModel,并设置为页面的BindingContext:
public MainPage()
{
    InitializeComponent();
    // 设置页面的绑定上下文
    BindingContext = new MainPageViewModel();
}

private void OnGetTextButtonClicked(object sender, EventArgs e)
{
    // 从BindingContext获取ViewModel实例
    var viewModel = (MainPageViewModel)BindingContext;
    // 获取绑定的文本内容
    string userInput = viewModel.UserInputText;
    
    Console.WriteLine($"用户输入的内容是:{userInput}");
}
  1. 最后在MainPage.xaml里给Entry设置Binding:
<Entry Placeholder="请输入内容..." Text="{Binding UserInputText}" />
<Button Text="获取输入文本" Clicked="OnGetTextButtonClicked" Margin="0,10,0,0" />

这个方法的好处是把UI和业务逻辑分开,后续添加更多控件或逻辑时,代码会更清晰。

内容的提问来源于stack exchange,提问作者Samuel Mungy

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 09:05:41