按索引 C# XAML 选择堆栈面板中的元素

本文关键字:元素 堆栈 索引 XAML 选择 | 更新日期: 2023-09-27 18:35:32

如何通过其Stackpanel索引选择要操作的元素?

早些时候,已经提出了这个问题,但该解决方案不适用于窗口应用程序,而仅适用于通用Windows应用程序。

按索引 C# XAML 选择堆栈面板中的元素

您可以访问 Children 属性。它返回一个带有索引器的属性,你可以使用索引访问该索引器。下面的示例在 StackPanel 中包含两个文本块,并将第二个文本块的文本设置为构造函数中的另一个值:

XAML:

<Window x:Class="TestWPF.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:TestWPF"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <StackPanel x:Name="pnl">
        <TextBlock Text="Hello" />
        <TextBlock Text="World" />
    </StackPanel>
</Window>

构造 函数:

public MainWindow()
{
    InitializeComponent();
    var txt = (TextBlock)pnl.Children[1];
    txt.Text = "Moon";
}

按索引访问子项的相关部分是:pnl.Children[index];