问题
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