我想在后台代码中创建多个框架,但是当在循环中创建框架并在内容中添加元素时,只有一个框架具有所有元素,而其他框架为空!为什么?
我的代码是:
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 });
}
这是结果:
您在循环的每次迭代中都使用WordDetail
的相同实例
相反,每次创建一个新实例
foreach (var dt in _viewModel.Items)
{
StackLayout WordDetail = new StackLayout();
我通过复制您的代码在本地复制了您的情况。我通过在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 } } });
}