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

我试图通过单击按钮访问在 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 中声明)文本。


慕村9548890
浏览 69回答 1
1回答

慕运维8079593

您可以使用数据绑定来设置和获取条目的文本。在 xaml 中<StackLayout>&nbsp; &nbsp; <Button Text="GetEntryTemplate" Clicked="Button_Clicked"/>&nbsp; &nbsp; <ListView x:Name="listView">&nbsp; &nbsp; &nbsp; &nbsp; <ListView.ItemTemplate>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <DataTemplate>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <ViewCell>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <Entry TextColor="Black" Text="{Binding Content,Mode=TwoWay}"/>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </ViewCell>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </DataTemplate>&nbsp; &nbsp; &nbsp; &nbsp; </ListView.ItemTemplate>&nbsp; &nbsp; </ListView></StackLayout>在你的代码后面创建一个模式(例如我的模型称为数据)public class Data{&nbsp; &nbsp; public string Content { get; set; }}并在 contentPagepublic partial class MainPage : ContentPage{&nbsp; &nbsp; public ObservableCollection<Data> MySource { get; set; }&nbsp; &nbsp; public MainPage()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; InitializeComponent();&nbsp; &nbsp; &nbsp; &nbsp; BindingContext = this;&nbsp; &nbsp; &nbsp; &nbsp; MySource = new ObservableCollection<Data>()&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; new Data() {Content="Entry_1" },&nbsp; &nbsp; &nbsp; &nbsp; };&nbsp; &nbsp; &nbsp; &nbsp; listView.ItemsSource = MySource;&nbsp; &nbsp; }&nbsp; &nbsp; private void Button_Clicked(object sender, EventArgs e)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; DisplayAlert("title", MySource[0].Content, "cancel");&nbsp; &nbsp; }}https://i.stack.imgur.com/DKzMR.gif
打开App,查看更多内容
随时随地看视频慕课网APP