【问题标题】:It is possible to revive an objects grid position from an xaml in wpf grid?可以从 wpf 网格中的 xaml 恢复对象网格位置吗?
【发布时间】:2017-01-13 00:54:04
【问题描述】:

我正在构建一个与已知游戏“生命游戏”非常相似的应用程序我暂时对 wither C# xaml 或 wpf 不太熟悉,但我相信这将是一个很好的学习方式一切都好起来了。因此,路上会有挣扎。

我制作了一个 10x10 的网格并用按钮归档,每个按钮都在网格中放置。为了跟踪每一代,我觉得我必须跟踪网格中的按钮位置。所以我想,如果我可以使用每个按钮网格位置 Y 轴和 X 轴。制作简单的方法来刺激每个按钮并比较两个 foor 循环内的位置并不难,每个轴一个。

我尝试通过投标恢复按钮网格位置,但我没有设法让它工作。

如果可以从网格中获得按钮网格药水,我该怎么做? 为了良好的实践,实现我的目标的更好方法是什么?

-- 隐藏代码。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using GOL.GameGrid;
using GOL.GameGrid.Props;

namespace GOL
{
    /// <summary>
    /// Interaction logic for frmGame.xaml
    /// </summary>
    public partial class frmGame : Window
    {

        string HelloWorld = "Hello World";
        private string btnDataContext;
        public frmGame()
        {
            InitializeComponent();
            MyBtnProps btnContent = new MyBtnProps() { Name = "T" };
            btnCollection();
        }
    private void btnReturn_Click(object sender, RoutedEventArgs e)
    {
        var newW = new MainWindow();
        newW.Show();
        this.Close();
    }
    private void btnCollection()
    {
        MyBtnProps btnDataContext = new MyBtnProps() { IsAlive = "T" };
        //btn00.DataContext = btnDataContext;
        var btnCollection = new List<Button>();
        #region Grid Buttons added to collection.
        btnCollection.Add(btn01);
        btnCollection.Add(btn01);
        btnCollection.Add(btn02);
        btnCollection.Add(btn03);
        btnCollection.Add(btn04);
        btnCollection.Add(btn05);
        btnCollection.Add(btn06);
        btnCollection.Add(btn07);
        btnCollection.Add(btn08);
        btnCollection.Add(btn09);

        btnCollection.Add(btn10);
        btnCollection.Add(btn11);
        btnCollection.Add(btn12);
        btnCollection.Add(btn13);
        btnCollection.Add(btn14);
        btnCollection.Add(btn15);
        btnCollection.Add(btn16);
        btnCollection.Add(btn17);
        btnCollection.Add(btn18);
        btnCollection.Add(btn19);

        btnCollection.Add(btn20);
        btnCollection.Add(btn21);
        btnCollection.Add(btn22);
        btnCollection.Add(btn23);
        btnCollection.Add(btn24);
        btnCollection.Add(btn25);
        btnCollection.Add(btn26);
        btnCollection.Add(btn27);
        btnCollection.Add(btn28);
        btnCollection.Add(btn29);

        btnCollection.Add(btn30);
        btnCollection.Add(btn31);
        btnCollection.Add(btn32);
        btnCollection.Add(btn33);
        btnCollection.Add(btn34);
        btnCollection.Add(btn35);
        btnCollection.Add(btn36);
        btnCollection.Add(btn37);
        btnCollection.Add(btn38);
        btnCollection.Add(btn39);

        btnCollection.Add(btn40);
        btnCollection.Add(btn41);
        btnCollection.Add(btn42);
        btnCollection.Add(btn43);
        btnCollection.Add(btn44);
        btnCollection.Add(btn45);
        btnCollection.Add(btn46);
        btnCollection.Add(btn47);
        btnCollection.Add(btn48);
        btnCollection.Add(btn49);

        btnCollection.Add(btn50);
        btnCollection.Add(btn51);
        btnCollection.Add(btn52);
        btnCollection.Add(btn53);
        btnCollection.Add(btn54);
        btnCollection.Add(btn55);
        btnCollection.Add(btn56);
        btnCollection.Add(btn57);
        btnCollection.Add(btn58);
        btnCollection.Add(btn59);

        btnCollection.Add(btn60);
        btnCollection.Add(btn61);
        btnCollection.Add(btn62);
        btnCollection.Add(btn63);
        btnCollection.Add(btn64);
        btnCollection.Add(btn65);
        btnCollection.Add(btn66);
        btnCollection.Add(btn67);
        btnCollection.Add(btn68);
        btnCollection.Add(btn69);

        btnCollection.Add(btn70);
        btnCollection.Add(btn71);
        btnCollection.Add(btn72);
        btnCollection.Add(btn73);
        btnCollection.Add(btn74);
        btnCollection.Add(btn75);
        btnCollection.Add(btn76);
        btnCollection.Add(btn77);
        btnCollection.Add(btn78);
        btnCollection.Add(btn79);

        btnCollection.Add(btn80);
        btnCollection.Add(btn81);
        btnCollection.Add(btn82);
        btnCollection.Add(btn83);
        btnCollection.Add(btn84);
        btnCollection.Add(btn85);
        btnCollection.Add(btn86);
        btnCollection.Add(btn87);
        btnCollection.Add(btn88);
        btnCollection.Add(btn89);

        btnCollection.Add(btn90);
        btnCollection.Add(btn91);
        btnCollection.Add(btn92);
        btnCollection.Add(btn93);
        btnCollection.Add(btn94);
        btnCollection.Add(btn95);
        btnCollection.Add(btn96);
        btnCollection.Add(btn97);
        btnCollection.Add(btn98);
        btnCollection.Add(btn99);
        #endregion Buttons added to collection.


        foreach (var item in btnCollection)
        {
            item.DataContext = btnDataContext;
            btn01.Background = new SolidColorBrush(Color.FromArgb(100, 102, 255, 179));
            btn00.Background = Brushes.Cornsilk;

            if (btn00.Background == Brushes.Cornsilk)
            {
                btn01.Background = Brushes.Azure;
            }
            else
            {
                btn01.Background = new SolidColorBrush(Color.FromArgb(100, 102, 120, 255));
            }

        }
    }

    #region LeftBtnClickEvents
    private void btn00_Click(object sender, RoutedEventArgs e)
    {
        btn00.Background = Brushes.Green;
    }
    private void btn01_Click(object sender, RoutedEventArgs e)
    {
        btn01.Background = Brushes.Green;
    }
    private void btn02_Click(object sender, RoutedEventArgs e)
    {
        btn02.Background = Brushes.Green;
    }
    private void btn03_Click(object sender, RoutedEventArgs e)
    {
        btn03.Background = Brushes.Green;
    }
    private void btn04_Click(object sender, RoutedEventArgs e)
    {
        btn04.Background = Brushes.Green;
    }
    private void btn05_Click(object sender, RoutedEventArgs e)
    {
        btn05.Background = Brushes.Green;
    }

    private void btn06_Click(object sender, RoutedEventArgs e)
    {
        btn60.Background = Brushes.Green;
    }
    private void btn07_Click(object sender, RoutedEventArgs e)
    {
        btn07.Background = Brushes.Green;
    }
    private void btn08_Click(object sender, RoutedEventArgs e)
    {
        btn08.Background = Brushes.Green;
    }
    private void btn09_Click(object sender, RoutedEventArgs e)
    {
        btn09.Background = Brushes.Green;
    }

    #endregion LeftBtnClickEvents

    #region RightBtnClickEvent
    private void btn00_RightClick(object sender, MouseButtonEventArgs e)
    {
        btn00.Background = Brushes.Red;
    }
    private void btn01_RightClick(object sender, MouseButtonEventArgs e)
    {
        btn01.Background = Brushes.Red;
    }
    private void btn02_RightClick(object sender, MouseButtonEventArgs e)
    {
        btn02.Background = Brushes.Red;
    }
    private void btn03_RightClick(object sender, MouseButtonEventArgs e)
    {
        btn03.Background = Brushes.Red;
    }
    private void btn04_RightClick(object sender, MouseButtonEventArgs e)
    {
        btn04.Background = Brushes.Red;
    }
    private void btn05_RightClick(object sender, MouseButtonEventArgs e)
    {
        btn05.Background = Brushes.Red;
    }
    private void btn06_RightClick(object sender, MouseButtonEventArgs e)
    {
        btn06.Background = Brushes.Red;
    }
    private void btn07_RightClick(object sender, MouseButtonEventArgs e)
    {
        btn07.Background = Brushes.Red;
    }
    private void btn08_RightClick(object sender, MouseButtonEventArgs e)
    {
        btn08.Background = Brushes.Red;
    }
    private void btn09_RightClick(object sender, MouseButtonEventArgs e)
    {
        btn09.Background = Brushes.Red;
    }
    #endregion RightBtnClickEvent
  }
}

-- xml代码。

<Window x:Class="GOL.frmGame"
        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:GOL"
        mc:Ignorable="d"
        Title="frmGame" Height="326.4" Width="388.2" Background="#f2f2f2">
    <Grid x:Name="WindowGrid" Height="Auto" Width="Auto">
        <Grid x:Name="btnNavbar" HorizontalAlignment="Left" Height="38" Margin="40,241,0,0" VerticalAlignment="Top" Width="300">
            <Grid.RowDefinitions>
                <RowDefinition/>
                <RowDefinition Height="1*"/>
            </Grid.RowDefinitions>
            <Grid.ColumnDefinitions>
                <ColumnDefinition/>
                <ColumnDefinition/>
                <ColumnDefinition Width="1*"/>
            </Grid.ColumnDefinitions>

            <Button x:Name="btnNewGen"  Content="New Generation"  Width="Auto" Height="Auto" Grid.Column="0" Grid.Row="0"/>
            <Button x:Name="btnLoadGen" Content="Load Generation" Width="Auto" Height="Auto" Grid.Column="0" Grid.Row="1"/>
            <Button x:Name="btnPlayGen" Content="PLAY"            Width="Auto" Height="Auto" Grid.Column="1" Grid.Row="0"/>
            <Button x:Name="button1"    Content="Magic"           Width="Auto" Height="Auto" Grid.Column="1" Grid.Row="2"/>
            <Button x:Name="btnSave"    Content="Save"            Width="Auto" Height="Auto" Grid.Column="3" Grid.Row="0"/>
            <Button x:Name="btnReturn"  Content="Menu"            Width="Auto" Height="Auto" Grid.Column="3" Grid.Row="1"/>
        </Grid>

        <Grid x:Name="GameBoard" HorizontalAlignment="Left" Height="200" Margin="80,20,0,0" VerticalAlignment="Top" Width="200" Background="Transparent">

            <Grid.RowDefinitions>

                <RowDefinition/>
                <RowDefinition/>
                <RowDefinition/>
                <RowDefinition/>
                <RowDefinition/>
                <RowDefinition/>
                <RowDefinition/>

            <RowDefinition/>
            <RowDefinition/>
            <RowDefinition Height="1*"/>

        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>

            <ColumnDefinition/>
            <ColumnDefinition/>
            <ColumnDefinition/>
            <ColumnDefinition/>
            <ColumnDefinition/>
            <ColumnDefinition/>
            <ColumnDefinition/>
            <ColumnDefinition/>
            <ColumnDefinition/>
            <ColumnDefinition Width="1*"/>

        </Grid.ColumnDefinitions>
        <Button x:Name="btn00" Content="" Grid.Column="0" Grid.Row="0" Height="Auto" Width="Auto" Click="btn00_Click" MouseRightButtonUp="btn00_RightClick" DataContext="{Binding IsAlive}"/>
        <Button x:Name="btn01" Content="" Grid.Column="0" Grid.Row="1" Height="Auto" Width="Auto" Click="btn01_Click" MouseRightButtonUp="btn01_RightClick" DataContext="{Binding IsAlive}"/>
        <Button x:Name="btn02" Content="" Grid.Column="0" Grid.Row="2" Height="Auto" Width="Auto" Click="btn02_Click" MouseRightButtonUp="btn02_RightClick" DataContext="{Binding IsAlive}"/>
        <Button x:Name="btn03" Content="" Grid.Column="0" Grid.Row="3" Height="Auto" Width="Auto" Click="btn03_Click" MouseRightButtonUp="btn03_RightClick" DataContext="{Binding IsAlive}"/>
        <Button x:Name="btn04" Content="" Grid.Column="0" Grid.Row="4" Height="Auto" Width="Auto" Click="btn04_Click" MouseRightButtonUp="btn04_RightClick" DataContext="{Binding IsAlive}"/>
        <Button x:Name="btn05" Content="" Grid.Column="0" Grid.Row="5" Height="Auto" Width="Auto" Click="btn05_Click" MouseRightButtonUp="btn05_RightClick" DataContext="{Binding IsAlive}"/>
        <Button x:Name="btn06" Content="" Grid.Column="0" Grid.Row="6" Height="Auto" Width="Auto" Click="btn06_Click" MouseRightButtonUp="btn06_RightClick" DataContext="{Binding IsAlive}"/>
        <Button x:Name="btn07" Content="" Grid.Column="0" Grid.Row="7" Height="Auto" Width="Auto" Click="btn07_Click" MouseRightButtonUp="btn07_RightClick" DataContext="{Binding IsAlive}"/>
        <Button x:Name="btn08" Content="" Grid.Column="0" Grid.Row="8" Height="Auto" Width="Auto" Click="btn08_Click" MouseRightButtonUp="btn08_RightClick" DataContext="{Binding IsAlive}"/>
        <Button x:Name="btn09" Content="" Grid.Column="0" Grid.Row="9" Height="Auto" Width="Auto" Click="btn09_Click" MouseRightButtonUp="btn09_RightClick" DataContext="{Binding IsAlive}"/>

        <Button x:Name="btn10" Content="" Grid.Column="1" Grid.Row="0" Height="Auto" Width="Auto"/>
        <Button x:Name="btn11" Content="" Grid.Column="1" Grid.Row="1" Height="Auto" Width="Auto"/>
        <Button x:Name="btn12" Content="" Grid.Column="1" Grid.Row="2" Height="Auto" Width="Auto"/>
        <Button x:Name="btn13" Content="" Grid.Column="1" Grid.Row="3" Height="Auto" Width="Auto"/>
        <Button x:Name="btn14" Content="" Grid.Column="1" Grid.Row="4" Height="Auto" Width="Auto"/>
        <Button x:Name="btn15" Content="" Grid.Column="1" Grid.Row="5" Height="Auto" Width="Auto"/>
        <Button x:Name="btn16" Content="" Grid.Column="1" Grid.Row="6" Height="Auto" Width="Auto"/>
        <Button x:Name="btn17" Content="" Grid.Column="1" Grid.Row="7" Height="Auto" Width="Auto"/>
        <Button x:Name="btn18" Content="" Grid.Column="1" Grid.Row="8" Height="Auto" Width="Auto"/>
        <Button x:Name="btn19" Content="" Grid.Column="1" Grid.Row="9" Height="Auto" Width="Auto"/>

        <Button x:Name="btn20" Content="" Grid.Column="2" Grid.Row="0" Height="Auto" Width="Auto"/>
        <Button x:Name="btn21" Content="" Grid.Column="2" Grid.Row="1" Height="Auto" Width="Auto"/>
        <Button x:Name="btn22" Content="" Grid.Column="2" Grid.Row="2" Height="Auto" Width="Auto"/>
        <Button x:Name="btn23" Content="" Grid.Column="2" Grid.Row="3" Height="Auto" Width="Auto"/>
        <Button x:Name="btn24" Content="" Grid.Column="2" Grid.Row="4" Height="Auto" Width="Auto"/>
        <Button x:Name="btn25" Content="" Grid.Column="2" Grid.Row="5" Height="Auto" Width="Auto"/>
        <Button x:Name="btn26" Content="" Grid.Column="2" Grid.Row="6" Height="Auto" Width="Auto"/>
        <Button x:Name="btn27" Content="" Grid.Column="2" Grid.Row="7" Height="Auto" Width="Auto"/>
        <Button x:Name="btn28" Content="" Grid.Column="2" Grid.Row="8" Height="Auto" Width="Auto"/>
        <Button x:Name="btn29" Content="" Grid.Column="2" Grid.Row="9" Height="Auto" Width="Auto"/>

        <Button x:Name="btn30" Content="" Grid.Column="3" Grid.Row="0" Height="Auto" Width="Auto"/>
        <Button x:Name="btn31" Content="" Grid.Column="3" Grid.Row="1" Height="Auto" Width="Auto"/>
        <Button x:Name="btn32" Content="" Grid.Column="3" Grid.Row="2" Height="Auto" Width="Auto"/>
        <Button x:Name="btn33" Content="" Grid.Column="3" Grid.Row="3" Height="Auto" Width="Auto"/>
        <Button x:Name="btn34" Content="" Grid.Column="3" Grid.Row="4" Height="Auto" Width="Auto"/>
        <Button x:Name="btn35" Content="" Grid.Column="3" Grid.Row="5" Height="Auto" Width="Auto"/>
        <Button x:Name="btn36" Content="" Grid.Column="3" Grid.Row="6" Height="Auto" Width="Auto"/>
        <Button x:Name="btn37" Content="" Grid.Column="3" Grid.Row="7" Height="Auto" Width="Auto"/>
        <Button x:Name="btn38" Content="" Grid.Column="3" Grid.Row="8" Height="Auto" Width="Auto"/>
        <Button x:Name="btn39" Content="" Grid.Column="3" Grid.Row="9" Height="Auto" Width="Auto"/>

        <Button x:Name="btn40" Content="" Grid.Column="4" Grid.Row="0" Height="Auto" Width="Auto"/>
        <Button x:Name="btn41" Content="" Grid.Column="4" Grid.Row="1" Height="Auto" Width="Auto"/>
        <Button x:Name="btn42" Content="" Grid.Column="4" Grid.Row="2" Height="Auto" Width="Auto"/>
        <Button x:Name="btn43" Content="" Grid.Column="4" Grid.Row="3" Height="Auto" Width="Auto"/>
        <Button x:Name="btn44" Content="" Grid.Column="4" Grid.Row="4" Height="Auto" Width="Auto"/>
        <Button x:Name="btn45" Content="" Grid.Column="4" Grid.Row="5" Height="Auto" Width="Auto"/>
        <Button x:Name="btn46" Content="" Grid.Column="4" Grid.Row="6" Height="Auto" Width="Auto"/>
        <Button x:Name="btn47" Content="" Grid.Column="4" Grid.Row="7" Height="Auto" Width="Auto"/>
        <Button x:Name="btn48" Content="" Grid.Column="4" Grid.Row="8" Height="Auto" Width="Auto"/>
        <Button x:Name="btn49" Content="" Grid.Column="4" Grid.Row="9" Height="Auto" Width="Auto"/>

        <Button x:Name="btn50" Content="" Grid.Column="5" Grid.Row="0" Height="Auto" Width="Auto"/>
        <Button x:Name="btn51" Content="" Grid.Column="5" Grid.Row="1" Height="Auto" Width="Auto"/>
        <Button x:Name="btn52" Content="" Grid.Column="5" Grid.Row="2" Height="Auto" Width="Auto"/>
        <Button x:Name="btn53" Content="" Grid.Column="5" Grid.Row="3" Height="Auto" Width="Auto"/>
        <Button x:Name="btn54" Content="" Grid.Column="5" Grid.Row="4" Height="Auto" Width="Auto"/>
        <Button x:Name="btn55" Content="" Grid.Column="5" Grid.Row="5" Height="Auto" Width="Auto"/>
        <Button x:Name="btn56" Content="" Grid.Column="5" Grid.Row="6" Height="Auto" Width="Auto"/>
        <Button x:Name="btn57" Content="" Grid.Column="5" Grid.Row="7" Height="Auto" Width="Auto"/>
        <Button x:Name="btn58" Content="" Grid.Column="5" Grid.Row="8" Height="Auto" Width="Auto"/>
        <Button x:Name="btn59" Content="" Grid.Column="5" Grid.Row="9" Height="Auto" Width="Auto"/>

        <Button x:Name="btn60" Content="" Grid.Column="6" Grid.Row="0" Height="Auto" Width="Auto"/>
        <Button x:Name="btn61" Content="" Grid.Column="6" Grid.Row="1" Height="Auto" Width="Auto"/>
        <Button x:Name="btn62" Content="" Grid.Column="6" Grid.Row="2" Height="Auto" Width="Auto"/>
        <Button x:Name="btn63" Content="" Grid.Column="6" Grid.Row="3" Height="Auto" Width="Auto"/>
        <Button x:Name="btn64" Content="" Grid.Column="6" Grid.Row="4" Height="Auto" Width="Auto"/>
        <Button x:Name="btn65" Content="" Grid.Column="6" Grid.Row="5" Height="Auto" Width="Auto"/>
        <Button x:Name="btn66" Content="" Grid.Column="6" Grid.Row="6" Height="Auto" Width="Auto"/>
        <Button x:Name="btn67" Content="" Grid.Column="6" Grid.Row="7" Height="Auto" Width="Auto"/>
        <Button x:Name="btn68" Content="" Grid.Column="6" Grid.Row="8" Height="Auto" Width="Auto"/>
        <Button x:Name="btn69" Content="" Grid.Column="6" Grid.Row="9" Height="Auto" Width="Auto"/>

        <Button x:Name="btn70" Content="" Grid.Column="7" Grid.Row="0" Height="Auto" Width="Auto"/>
        <Button x:Name="btn71" Content="" Grid.Column="7" Grid.Row="1" Height="Auto" Width="Auto"/>
        <Button x:Name="btn72" Content="" Grid.Column="7" Grid.Row="2" Height="Auto" Width="Auto"/>
        <Button x:Name="btn73" Content="" Grid.Column="7" Grid.Row="3" Height="Auto" Width="Auto"/>
        <Button x:Name="btn74" Content="" Grid.Column="7" Grid.Row="4" Height="Auto" Width="Auto"/>
        <Button x:Name="btn75" Content="" Grid.Column="7" Grid.Row="5" Height="Auto" Width="Auto"/>
        <Button x:Name="btn76" Content="" Grid.Column="7" Grid.Row="6" Height="Auto" Width="Auto"/>
        <Button x:Name="btn77" Content="" Grid.Column="7" Grid.Row="7" Height="Auto" Width="Auto"/>
        <Button x:Name="btn78" Content="" Grid.Column="7" Grid.Row="8" Height="Auto" Width="Auto"/>
        <Button x:Name="btn79" Content="" Grid.Column="7" Grid.Row="9" Height="Auto" Width="Auto"/>

        <Button x:Name="btn80" Content="" Grid.Column="8" Grid.Row="0" Height="Auto" Width="Auto"/>
        <Button x:Name="btn81" Content="" Grid.Column="8" Grid.Row="1" Height="Auto" Width="Auto"/>
        <Button x:Name="btn82" Content="" Grid.Column="8" Grid.Row="2" Height="Auto" Width="Auto"/>
        <Button x:Name="btn83" Content="" Grid.Column="8" Grid.Row="3" Height="Auto" Width="Auto"/>
        <Button x:Name="btn84" Content="" Grid.Column="8" Grid.Row="4" Height="Auto" Width="Auto"/>
        <Button x:Name="btn85" Content="" Grid.Column="8" Grid.Row="5" Height="Auto" Width="Auto"/>
        <Button x:Name="btn86" Content="" Grid.Column="8" Grid.Row="6" Height="Auto" Width="Auto"/>
        <Button x:Name="btn87" Content="" Grid.Column="8" Grid.Row="7" Height="Auto" Width="Auto"/>
        <Button x:Name="btn88" Content="" Grid.Column="8" Grid.Row="8" Height="Auto" Width="Auto"/>
        <Button x:Name="btn89" Content="" Grid.Column="8" Grid.Row="9" Height="Auto" Width="Auto"/>

        <Button x:Name="btn90" Content="" Grid.Column="9" Grid.Row="0" Height="Auto" Width="Auto"/>
        <Button x:Name="btn91" Content="" Grid.Column="9" Grid.Row="1" Height="Auto" Width="Auto"/>
        <Button x:Name="btn92" Content="" Grid.Column="9" Grid.Row="2" Height="Auto" Width="Auto"/>
        <Button x:Name="btn93" Content="" Grid.Column="9" Grid.Row="3" Height="Auto" Width="Auto"/>
        <Button x:Name="btn94" Content="" Grid.Column="9" Grid.Row="4" Height="Auto" Width="Auto"/>
        <Button x:Name="btn95" Content="" Grid.Column="9" Grid.Row="5" Height="Auto" Width="Auto"/>
        <Button x:Name="btn96" Content="" Grid.Column="9" Grid.Row="6" Height="Auto" Width="Auto"/>
        <Button x:Name="btn97" Content="" Grid.Column="9" Grid.Row="7" Height="Auto" Width="Auto"/>
        <Button x:Name="btn98" Content="" Grid.Column="9" Grid.Row="8" Height="Auto" Width="Auto"/>
        <Button x:Name="btn99" Content="" Grid.Column="9" Grid.Row="9" Height="Auto" Width="Auto"/>
    </Grid>
</Grid>

【问题讨论】:

    标签: c# wpf visual-studio xaml


    【解决方案1】:

    您只需几行 XAML 代码即可创建整个网格。 ;-)

    使用 MVVM 的魔力

    创建用于管理按钮的 ViewModel 类。让它拥有按钮数据的ObservableCollection。我还创建了一个变量来设置我们网格的列数。

    public ObservableCollection<GridButton> GridButtonList { get; set; } = new ObservableCollection<GridButton>();
    public int GridColumns { get; set; }
    

    然后,创建用于存储每个按钮数据的基本类——例如背景和定义的鼠标左键和右键单击动作。使用属性而不是常规变量很重要,因为它允许您直接在 XAML 绑定中使用它们。您可能需要扩展它们以使用 PropertyChanged 事件,我稍后会解释。

    class GridButton
    {
        public string Text { get; set; }
        public Brush Background { get; set; }
        public ICommand OnLeftClick { get; set; }
        public ICommand OnRightClick { get; set; }
    }
    

    接下来,我们可以创建一个基于 UserControl 的视图来仅显示这些按钮。

    <UserControl ...>
        <UserControl.DataContext>
            <!-- Binding previously created ViewModel to our View -->
            <ViewModel:ButtonGridViewModel />
        </UserControl.DataContext>
    
        <ItemsControl ItemsSource="{Binding GridButtonList}">
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <UniformGrid Columns="{Binding GridColumns}" />
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <Button Content="{Binding Text}" Background="{Binding Background}" Command="{Binding OnClick}" CommandParameter="{Binding}">
                        <Button.InputBindings>
                            <MouseBinding Gesture="RightClick" Command="{Binding OnRightClick}" CommandParameter="{Binding}" />
                        </Button.InputBindings>
                    </Button>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>
    </UserControl>
    

    请注意,我们将从 ViewModel 中定义的变量 GridButtonList 导入所有按钮。无论您拥有多少按钮,XAML 从现在起不会改变。

    我推荐使用UniformGrid,它会自动安排飞机上的物品。您可以选择将行和列定义为网格的提示。好处是每个项目都将具有相同的宽度和高度,这似乎非常适合您的应用程序。

    我们提供对象集合GridButton,这意味着ItemsControl 中的每个项目都属于该类型。我们指示它使用来自GridButton 类的数据为每个项目呈现Button。对于标准左键单击,我们将使用默认的Command 属性和GridButton.OnLeftClick 中定义的适当操作。至于右键单击,我们将使用InputBindings,在这里我们可以定义详细的手势来触发下一个动作——GridButton.OnRightClick。可用鼠标手势的完整列表位于documentation。与MouseBinding 类似的是KeyBinding,它支持基于键盘手势的触发命令。

    填充按钮的集合

    以下代码将创建 81 个具有单独操作的按钮。由于 XAML 绑定,每个按钮内部都会有一个文本,对应于其位置,格式为 XxY。请注意,我们只能使用一个循环来创建一个网格,这要归功于 Modulo operator

    GridColumns = 9;
    
    var itemCount = Math.Pow(GridColumns, 2);
    for (var i = 0; i < itemCount; ++i)
    {
        var btn = new GridButton()
        {
            Text = string.Format("{0}x{1}", i % GridColumns + 1, i / GridColumns + 1),
            OnClick = new RelayCommand<GridButton>((b) =>
            {
                b.Background = Brushes.Green;
            }),
            OnRightClick = new RelayCommand<GridButton>((b) =>
            {
                b.Background = Brushes.Red;
            })
        };
        GridButtonList.Add(btn);
    }
    

    助手类

    我使用了 2 个类来帮助使一切正常工作,RelayCommand 支持 CommandObservableObject 帮助我们实现数据绑定。我在下面列出了这两个:

    internal class ObservableObject : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
    
        protected void RaisePropertyChangedEvent(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
    
    public class RelayCommand<T> : ICommand
    {
        #region Fields
    
        readonly Action<T> _execute = null;
        readonly Predicate<T> _canExecute = null;
    
        #endregion
    
        #region Constructors
    
        /// <summary>
        /// Initializes a new instance of <see cref="DelegateCommand{T}"/>.
        /// </summary>
        /// <param name="execute">Delegate to execute when Execute is called on the command.  This can be null to just hook up a CanExecute delegate.</param>
        /// <remarks><seealso cref="CanExecute"/> will always return true.</remarks>
        public RelayCommand(Action<T> execute)
            : this(execute, null)
        {
        }
    
        /// <summary>
        /// Creates a new command.
        /// </summary>
        /// <param name="execute">The execution logic.</param>
        /// <param name="canExecute">The execution status logic.</param>
        public RelayCommand(Action<T> execute, Predicate<T> canExecute)
        {
            if (execute == null)
                throw new ArgumentNullException("execute");
    
            _execute = execute;
            _canExecute = canExecute;
        }
    
        #endregion
    
        #region ICommand Members
    
        ///<summary>
        ///Defines the method that determines whether the command can execute in its current state.
        ///</summary>
        ///<param name="parameter">Data used by the command.  If the command does not require data to be passed, this object can be set to null.</param>
        ///<returns>
        ///true if this command can be executed; otherwise, false.
        ///</returns>
        public bool CanExecute(object parameter)
        {
            return _canExecute == null ? true : _canExecute((T)parameter);
        }
    
        ///<summary>
        ///Occurs when changes occur that affect whether or not the command should execute.
        ///</summary>
        public event EventHandler CanExecuteChanged
        {
            add { CommandManager.RequerySuggested += value; }
            remove { CommandManager.RequerySuggested -= value; }
        }
    
        ///<summary>
        ///Defines the method to be called when the command is invoked.
        ///</summary>
        ///<param name="parameter">Data used by the command. If the command does not require data to be passed, this object can be set to <see langword="null" />.</param>
        public void Execute(object parameter)
        {
            _execute((T)parameter);
        }
    
        #endregion
    }
    

    工作示例

    我冒昧地创建了示例项目供您分析。你可以在 GitHub 上查看:https://github.com/xerif-examples/WPF-ButtonGridTest

    我建议使用 MVVM 来编写更少的代码。

    希望对您有所帮助,
    ~维克托

    【讨论】:

    • 这看起来很像我正在寻找的东西,我相信构建 mroe 功能应该不难。 :) 感谢您提供快速而良好的答案。 ~托拜厄斯奥尔森
    • 我很高兴它有帮助!如果它完全回答了您的问题,您可以将其标记为已接受的答案。 ;-)
    【解决方案2】:

    您可以使用 UIElement 的 GetValue() 函数,在本例中为 Button,然后将返回的对象转换为适当的类型,在本例中为 int。

    int row = (int)button.GetValue(Grid.RowProperty);
    int col = (int)button.GetValue(Grid.ColumnProperty);
    

    然后,您可以在 for 循环中使用这些值来执行您需要执行的任何操作。

    【讨论】:

    • 为了使这个解决方案起作用,我假设我必须创建按钮控件的实例并在那里构建属性。我一直在研究,但它接缝有点乱,可能不难做到,但对于我目前的水平来说有点乱。如我错了请纠正我。 :) ~托比亚斯奥尔森
    • 根据您上面的代码,您已经有一个按钮集合,称为 btnCollection,您可以使用它来迭代,并且您已经定义了按钮的 Grid.RowProperty 和 Grid.ColumnProperty XAML。我会说,@Wiktor 的解决方案很优雅,并解释了如何最好地使用 MVVM,这是通常用于 WPF 的设计模式,但是对于一个快速简单的解决方案,您应该可以轻松实现我的答案。
    猜你喜欢
    • 1970-01-01
    • 2011-02-23
    • 2010-12-06
    • 2013-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-02
    • 1970-01-01
    相关资源
    最近更新 更多