在Xamarin.Forms中的代码后面创建多个框架

问题描述 投票:0回答:2

我想在后台代码中创建多个框架,但是当在循环中创建框架并在内容中添加元素时,只有一个框架具有所有元素,而其他框架为空!为什么?

我的代码是:

private void searchResults_ItemTapped(object sender, ItemTappedEventArgs e)
{
    searchResults.IsVisible = false;

    Indexes Indexes = (Indexes)searchResults.SelectedItem;
    _viewModel.Items.Add(db.RequestToJson(Indexes.Index));

    searchbar.Text = string.Empty;




    StackLayout Words = new StackLayout();
    StackLayout WordDetail = new StackLayout();

    foreach (var dt in _viewModel.Items)
    {
        AddTextToLabel(nameof(dt.Word), dt.Word, WordDetail);
        var BaseLang = dt.BaseLang;
        AddTextToLabel(nameof(BaseLang.Meaning), BaseLang.Meaning, WordDetail);
        Words.Children.Add(new Frame { BackgroundColor = Color.FromHex("2196F3"), Padding = 5, HasShadow = false, Margin = new Thickness(10, 10, 80, 10), Content = new StackLayout { Children = { WordDetail } } });
    }
    SearchResult.Content = Words;
    SearchResult.IsVisible = true;
}
private void AddTextToLabel(string title, string data, StackLayout worddetail)
{
    worddetail.Children.Add(new Label { Text = title + ":", FontAttributes = FontAttributes.Bold, TextColor = Color.White });
    worddetail.Children.Add(new Label { Text = data, TextColor = Color.White });
}

这是结果:

enter image description here

xaml xamarin xamarin.forms xamarin.android xamarin.ios
2个回答
0
投票

您在循环的每次迭代中都使用WordDetail的相同实例

相反,每次创建一个新实例

foreach (var dt in _viewModel.Items)
{
  StackLayout WordDetail = new StackLayout();

0
投票

我通过复制您的代码在本地复制了您的情况。我通过在foreach中移动WordDetail声明来解决它,如下所示:

StackLayout Words = new StackLayout();

foreach (var dt in _viewModel.Items)
{
    StackLayout WordDetail = new StackLayout();
    AddTextToLabel(nameof(dt.Word), dt.Word, WordDetail);
    var BaseLang = dt.BaseLang;
    AddTextToLabel(nameof(BaseLang.Meaning), BaseLang.Meaning, WordDetail);
    Words.Children.Add(new Frame { BackgroundColor = Color.FromHex("2196F3"), Padding = 5, HasShadow = false, Margin = new Thickness(10, 10, 80, 10), Content = new StackLayout { Children = { WordDetail } } });
}
© www.soinside.com 2019 - 2024. All rights reserved.