c# - 动态创建 StackPanel 并在后面的代码中引用它们中的任何一个

标签 c# wpf xaml uwp

最简单的形式...

我想创建任意数量的 StackPanel,然后在其中添加矩形。例如,当我单击“开始”按钮时,能够更改任何一个矩形的填充颜色。全部在代码隐藏中。

如有任何帮助,我们将不胜感激。

例如,如果我们最喜欢的啤酒写了框架我可以这样做:

XAML:

<Page
    x:Class="Test2.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:Test2"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <Grid Background="White">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <StackPanel Orientation="Horizontal">
            <Button Name="StartButton" Content="Start" Click="StartButton_Click" Height="30" Width="200" Margin="5"/>
        </StackPanel>

        <StackPanel Grid.Row="1" Name="myStackPanel" VerticalAlignment="Top"/>

    </Grid>
</Page>

代码隐藏:

namespace Test2
{
    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();

            for (var i = 0; i < 5; i++) // The 5 here could be any number
            {
                myStackPanel.Children.Add(new StackPanel
                {
                    Name = "myPanel" + i,
                    Orientation = Orientation.Horizontal
                });

                for (var j = 0; j < 10; j++) // The 10 here could be any number
                {
                    ("myPanel" + i).Children.Add(new Rectangle
                    {
                        Name = "myRectangle" + i + "-" + j,
                        Fill = new SolidColorBrush(Colors.Black),
                        Width = 20,
                        Height = 20,
                        Margin = new Thickness(1)
                    });
                }
            }
        }

        private void StartButton_Click(object sender, RoutedEventArgs e)
        {
            // E.G. To change the Fill color of Rectangle4 in StackPanel2

            ("myRectangle" + 2 + "-" + 4).Fill = new SolidColorBrush(Colors.Red);
        }
    }
}

最佳答案

首先,要添加矩形形状,我们可以创建 StackPanel 的实例并操作其子元素:

for (var i = 0; i < 5; i++) // The 5 here could be any number
{
                StackPanel sp = new StackPanel
                {
                    Name = "myPanel" + i,
                    Orientation = Orientation.Horizontal
                };
                myStackPanel.Children.Add(sp);

                for (var j = 0; j < 10; j++) // The 10 here could be any number
                {
                    sp.Children.Add(new Rectangle
                    {
                        Name = "myRectangle" + i + "-" + j,
                        Fill = new SolidColorBrush(Colors.Black),
                        Width = 20,
                        Height = 20,
                        Margin = new Thickness(1)
                    });
                }
}

Then to be able to change the Fill color of any one of the Rectangles when I click the Start Button for instance. All in Code Behind.

正如tgpdyk所说,我们需要使用VisualTreeHelper来找到指定的矩形形状。

辅助类:

public static class FrameworkElementExtensions
{
        public static T TraverseCTFindShape<T>(DependencyObject root, String name) where T : Windows.UI.Xaml.Shapes.Shape
        {
            T control = null;

            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(root); i++)
            {
                var child = VisualTreeHelper.GetChild(root, i);

                string childName = child.GetValue(FrameworkElement.NameProperty) as string;
                control = child as T;

                if (childName == name)
                {
                    return control;
                }
                else
                {
                    control = TraverseCTFindShape<T>(child, name);

                    if (control != null)
                    {
                        return control;
                    }
                }
            }

            return control;
        }
}

使用方法:

private void StartButton_Click(object sender, RoutedEventArgs e)
{
            // E.G. To change the Fill color of Rectangle4 in StackPanel2
            var rec = FrameworkElementExtensions.TraverseCTFindShape<Shape>(myStackPanel, "myRectangle" + 2 + "-" + 4);
            rec.Fill = new SolidColorBrush(Colors.Red);
}

enter image description here

我已将样本上传到 Github repository

关于c# - 动态创建 StackPanel 并在后面的代码中引用它们中的任何一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34369341/

相关文章:

WPF : Binding Order

c# - 如何刷新ViewModel来更新View

c# - 如何使用高级 OpenType 功能编写程序?

c# - 如何在 C# 中使用网络用户

c# - WPF/C# - 以编程方式创建和使用单选按钮的示例

wpf - 访问现有的 WPF 应用程序实例?

c# - 如何知道为什么我的 WPF 窗口这么大?

c# - 从事件触发器内更改属性

c# - EnvironmentPermission Deny 在 .Net 4.0 中已过时,有替代方案吗?

c# - 捕获 SQLException 并重试的良好 C# 编码风格是什么