Select element within StackPanel by index C# XAML

て烟熏妆下的殇ゞ 提交于 2019-12-25 04:04:29

问题


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

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


回答1:


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:

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>

Constructor:

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

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



来源:https://stackoverflow.com/questions/35523569/select-element-within-stackpanel-by-index-c-sharp-xaml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!