如何通过Stackpanel
索引选择要操作的元素?
早些时候,已经提出了this问题,但该解决方案在窗口应用程序中不起作用,但仅在通用Windows应用程序中起作用。
答案 0 :(得分:1)
您可以访问Children
媒体资源。它返回一个带有索引器的属性,您可以使用索引访问该属性。以下示例在StackPanel中包含两个TextBlock,并将第二个文本的文本设置为构造函数中的另一个值:
<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];