c# - 如何对按钮 WPF 进行分组?

标签 c# wpf xaml grid

我制作了一个充满按钮的 3x3 网格。
我需要以某种方式对它们进行分组,以便对它们使用 Foreach。
我该怎么做?

我搜索了互联网,但没有找到任何有用的信息。
我还有一个永远不会更改的按钮,因此调用所有按钮进行更改不是一个答案。

最佳答案

你真的应该考虑实现 MVVM 模式,在大多数情况下你不需要引用任何按钮,因为它是你的 ViewModel 的一部分,你可以循环遍历你想要更改的集合。

但是,根据您的信息,您有类似 3x3 的东西,每个按钮都有按钮吗?

<Grid x:Name="myGrid">
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="33*"/>
        <ColumnDefinition Width="33*"/>
        <ColumnDefinition Width="33*"/>
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="33*"/>
        <RowDefinition Height="33*"/>
        <RowDefinition Height="33*"/>
    </Grid.RowDefinitions>
    <Button Content="1" Grid.Row="0" Grid.Column="0" ></Button>
    <Button Content="2" Grid.Row="0" Grid.Column="1" ></Button>
    <Button Content="3" Grid.Row="0" Grid.Column="2" ></Button>
    <Button Content="4" Grid.Row="1" Grid.Column="0" ></Button>
    <Button Content="5" Grid.Row="1" Grid.Column="1" ></Button>
    <Button Content="6" Grid.Row="1" Grid.Column="2" ></Button>
    <Button Content="7" Grid.Row="2" Grid.Column="0" ></Button>
    <Button Content="8" Grid.Row="2" Grid.Column="1" ></Button>
    <Button Content="9" Grid.Row="2" Grid.Column="2" ></Button>
</Grid>

然后在后面的代码中很简单 foreach 遍历 Grid 的 child

foreach (Button b in this.myGrid.Children)
{
    // do whatever you want with b
    // b.Content = "I'm a button";
}

你也可以给每个按钮加上一个特定的标识符,甚至循环它们

foreach (Button b in this.myGrid.Children)
{
    if(b.Tag == "main_buttons")
    {
        // do whatever you want with b when b.Tag is what you want
    }
}

enter image description here

关于c# - 如何对按钮 WPF 进行分组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27208158/

相关文章:

c# - 在Regex Replace C#中需要帮助

c# - 将没有根元素名称的具有多种类型的列表序列化为 XML

.net - WPF 设计器抛出奇怪的错误

c# - 使用 FedEx 运送服务 WSDL 创建 FedEx 运送文件

c# - 使用 LINQ 或 Lambda 从列表中删除实例?

WPF 菜单项边框

c# - 数据绑定(bind)到方法的输出

c# - WPF - 如何获取绑定(bind)到 ListBoxItem 的对象

windows - Xaml + Directx Fullscene Windows 10 移动版

c# - 发布版本中抽象页面的问题