【问题标题】:How to get text from entry如何从条目中获取文本
【发布时间】:2025-11-24 14:40:01
【问题描述】:

我创建一个条目使用

 <Entry Placeholder="Reply..."/>

它在 ListView > ItemTemplate > DataTemplate > ViewCell 内

问题是我需要一种方法,一旦用户单击该 ViewCell 中的提交按钮,它就会获取该单元格中条目的文本。我正在使用 Binding 来设置值,所以我不知道如何获取文本。

【问题讨论】:

  • 请分享相关的viewcell代码。条目的文本默认模式是双向的,因此当您更改条目文本时,您的绑定对象也会更改
  • @DiegoRafaelSouza 这就是我所有的相关代码
  • 您通过ListViewItemsSource 的每个element 访问数据。这是最干净的方法。你只需要得到合适的索引

标签: c# xamarin xamarin.forms


【解决方案1】:

当你处理按钮的点击事件时,假设你使用事件处理器来监听Clicked事件,你可以获取到按钮的BindingContext(也应该和整个BindingContext一样)视单元)。

像这样:

public void OnButtonClicked(object sender, EventArgs e)
{
    // Assuming the List bound to the ListView contains "MyObject" objects,
    // for example List<MyObject>:

    var myObjectBoundToViewCell = (MyObject)((Button)sender).BindingContext;

    // and now use myObjectBoundToViewCell to get the text that is bound from the Entry
}

【讨论】:

  • 我没有将文本绑定到条目?这是我的代码gist.github.com/KingBlueSapphire/…我找不到任何方法来获取条目
  • 我在“myObjectBoundToViewCell”中找不到与条目相关的任何内容
  • 也许您需要将 Text="{Binding PostReply}" 添加到您的 中。虽然我不确定这是否是您要使用的字段。但是你至少需要将 Entry 的 Text 属性绑定到 MessageObject 中的某个属性
【解决方案2】:

看到您的代码,我可以注意到为什么@sme 的答案不适合您。您对bindingsxaml 的使用非常混乱和糟糕,我很确定转为MVVM 是您现在可以做的最好的事情。

但是,如果你坚持要保持现在的代码,你可以添加绑定到 Entry 的 text 属性的回复文本,如下所示:

<Entry Placeholder="Reply..." 
       HorizontalOptions="FillAndExpand" 
       Margin="0, 0, 0, 5"
       Text="{Binding Reply}"/>

因此,当您将整个 MessageObjectobject 发送到 tap 命令时,您将能够以这种方式获取文本内容:

public void ReplyCommandClick(string id, object msg)
{
    MessageObject message = (MessageObject) msg;
    message.ShowReplyField = message.ShowReplyField ? false : true;
    //var viewcell = (MessageObject)((Label)msg).BindingContext;
    //viewcell. // There were no options for the entry
    var reply = msg.Reply;
    SendReply(id, msg, reply);
} 

【讨论】:

  • 当您使用绑定到ViewCell 的命令时,通常它只是实际的模型。或者为每个单元格添加事件处理程序时的公共事件参数(发送者,事件)
  • @mr5 对不起,我听不懂你的意思。我的英语太差了