本文介绍了按索引 C# XAML 在 StackPanel 中选择元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I select an element for manipulation by its Stackpanel index?

早些时候,有人问过这个问题,但该解决方案在窗口应用程序中不起作用,而只能在通用 Windows 应用程序中使用.

Earlier on, this question has been asked, but the solution does not work in window applications, but only in Universal Windows Applications.

推荐答案

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

You can access the Children property. It returns a property with an indexer that you can access with an index. The following sample contains two TextBlocks in a StackPanel and sets the text of the second one to another value in the constructor:

<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";
}

通过索引访问child的相关部分是:pnl.Children[index];

The relevant part for accessing the child by index is: pnl.Children[index];

这篇关于按索引 C# XAML 在 StackPanel 中选择元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 12:41