首先,我是初學者。
我想訪問堆疊布局中不同型別的每個子元素。
我試過但找不到任何解決方案。
我正在使用 Microsoft Visual Studio Community 2019 版本 16.11.9。
主頁.xaml
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="NewExp.MainPage"
x:Name="mainPage">
<StackLayout x:Name="first">
<StackLayout x:Name="second">
<Label Text="label1"/>
<Label Text="label2"/>
<Label Text="label3"/>
<Label Text="label4"/>
<Label Text="label5"/>
</StackLayout>
<AbsoluteLayout x:Name="third">
<Button Text="BTN" Clicked="Button_Clicked" />
</AbsoluteLayout>
</StackLayout>
</ContentPage>
MainPage.xaml.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
namespace NewExp
{
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}
private void Button_Clicked(object sender, EventArgs e)
{
Type type;
Label label;
// I want to access each child and change there's property eg. Text
var _list = second.Children.ToList();
for (int i = 0; i < _list.Count; i )
{
// Not working
//_list[i].Text = "New Text";
// Not working
//type = _list[i].GetType();
//var _lst = (type)_list[i];
//_lst.Text = "New Text";
// Working, but I need to know previously that it is a Label
// and this is not real world case.
// I also used Linq, but no benefit
label = (Label)_list[i];
label.Text = "New Text";
}
}
}
}
任何建議將是最明顯的。提前致謝。
uj5u.com熱心網友回復:
正如我在評論中指出的那樣,以這種方式直接修改 UI 通常是一個壞主意,最好通過資料系結來實作。但是,如果你必須這樣做,這樣的事情應該可以作業
foreach (var c in second.Children)
{
if (c is Label l)
{
l.Text = "some new text";
}
// repeat for any other types
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/420002.html
標籤:
上一篇:有沒有辦法使用C#在VisualStudio中動態更改文本框的文本,以便該值是來自其他文本框的值的總和?
下一篇:如何在顫振中制作強密碼?[復制]
