为了账号安全,请及时绑定邮箱和手机立即绑定

如何访问代码隐藏中的元素,它在 Xamarin.Foms 的 xaml 页面中的

如何访问代码隐藏中的元素,它在 Xamarin.Foms 的 xaml 页面中的

C#
慕村9548890 2022-11-21 21:48:04
我试图通过单击按钮访问在 DataTemplate 中声明的条目,该条目实际上位于 ListView 的 ItemTemplate 中。<StackLayout>    <Button Text="GetEntryTemplate" Clicked="Button_Clicked"/>    <ListView x:Name="listView" ItemsSource="{Binding Customer}">        <ListView.ItemTemplate>            <DataTemplate>                <ViewCell>                    <Entry Text="Xamarin"/>                </ViewCell>            </DataTemplate>        </ListView.ItemTemplate>    </ListView></StackLayout>    private void Button_Clicked(object sender, EventArgs e)    {        var loadedTemplate = listView.ItemTemplate.CreateContent();        var view = ((loadedTemplate as ViewCell).View as Entry).Text;                }我试过 CreateContent(),它实际上并没有显示运行时的变化。有人可以帮我解决这个问题吗?简而言之,我需要通过单击按钮访问现有条目实例(在 DataTemplate 中声明)文本。
查看完整描述

1 回答

?
慕运维8079593

TA贡献1876条经验 获得超5个赞

您可以使用数据绑定来设置和获取条目的文本。


在 xaml 中


<StackLayout>


    <Button Text="GetEntryTemplate" Clicked="Button_Clicked"/>


    <ListView x:Name="listView">


        <ListView.ItemTemplate>


            <DataTemplate>


                <ViewCell>


                    <Entry TextColor="Black" Text="{Binding Content,Mode=TwoWay}"/>


                </ViewCell>


            </DataTemplate>


        </ListView.ItemTemplate>


    </ListView>


</StackLayout>

在你的代码后面


创建一个模式(例如我的模型称为数据)


public class Data

{

    public string Content { get; set; }

}

并在 contentPage


public partial class MainPage : ContentPage

{


    public ObservableCollection<Data> MySource { get; set; }


    public MainPage()

    {

        InitializeComponent();


        BindingContext = this;




        MySource = new ObservableCollection<Data>()

        {

          new Data() {Content="Entry_1" },

        };


        listView.ItemsSource = MySource;


    }




    private void Button_Clicked(object sender, EventArgs e)

    {


        DisplayAlert("title", MySource[0].Content, "cancel");


    }

}

https://i.stack.imgur.com/DKzMR.gif

查看完整回答
反对 回复 2022-11-21
  • 1 回答
  • 0 关注
  • 68 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信