C# 我可以访问codebehind中数组中的XAML元素吗?
我一直在四处寻找,但没能找到这方面的任何东西。我正在尝试使用Visual Studio 2013 Pro开始用C#制作Windows 8.1应用程序。我希望能够访问数组中的多个元素(特别是按钮或文本块),因为这对于开发诸如棋盘游戏之类的东西更方便。例如,如果我正在开发tic-tac-toe,我可能会使用如下一系列按钮:C# 我可以访问codebehind中数组中的XAML元素吗?,c#,wpf,xaml,visual-studio-2013,windows-8.1,C#,Wpf,Xaml,Visual Studio 2013,Windows 8.1,我一直在四处寻找,但没能找到这方面的任何东西。我正在尝试使用Visual Studio 2013 Pro开始用C#制作Windows 8.1应用程序。我希望能够访问数组中的多个元素(特别是按钮或文本块),因为这对于开发诸如棋盘游戏之类的东西更方便。例如,如果我正在开发tic-tac-toe,我可能会使用如下一系列按钮: <Grid> <Button Name="Cell00"/> <Button Name="Cell01"/> <
<Grid>
<Button Name="Cell00"/>
<Button Name="Cell01"/>
<Button Name="Cell02"/>
<Button Name="Cell10"/>
<Button Name="Cell11"/>
<Button Name="Cell12"/>
<Button Name="Cell20"/>
<Button Name="Cell21"/>
<Button Name="Cell22"/>
<Grid/>
这种类型的代码将非常麻烦。我想用一种可以检查数组是否有循环的方式来编写它
我意识到使用tic-tac-toe,使用蛮力编写代码是相当容易的,但这是我想到的第一个例子。像Reversi或Go这样的其他游戏不会像这样很好地工作,因为无论是纯粹的大小还是放置的碎片都会改变它们所放置的单元格以外的其他单元格
如果您有任何帮助,我们将不胜感激。这是非常可能的。只需声明一个数组变量:
private Button[] _buttonArray;
填充数组一次,可能在构造函数中:
_buttonArray = new[] {Cell00, Cell01, .... , Cell22};
现在可以通过
\u buttonArray
访问所有按钮。这不是使用WPF的正确方法。WPF被设计为使用数据绑定……直接创建和操作UI元素是一种糟糕的形式。关于这方面的帖子/讨论/问题比你想象的要多,我让你自己去研究。同时,这就是“正确”使用WPF的方式:
首先使用NuGet将MVVM lite添加到项目中,以便获得ViewModelBase
类并为单个单元格创建视图模型:
public class Cell : ViewModelBase
{
private string _Text;
public string Text
{
get { return _Text; }
set { _Text = value; RaisePropertyChanged(() => this.Text); }
}
}
在一个级别上,您需要一个主模型来封装这些组件的数组,这是您通常执行所有游戏逻辑的地方:
public class MainModel : ViewModelBase
{
private ObservableCollection<Cell> _Cells;
public ObservableCollection<Cell> Cells
{
get { return _Cells; }
set { _Cells = value; RaisePropertyChanged(() => this.Cells); }
}
public MainModel()
{
this.Cells = new ObservableCollection<Cell>(
Enumerable.Range(1, 100)
.Select(i => new Cell { Text = i.ToString() })
);
}
}
现在,您的XAML控件需要绑定到此数据。ItemsControl用于呈现元素集合,因此请使用其中一个元素并将其绑定到数组。您希望它们显示在二维网格中,因此将ItemsPanelTemplate替换为WrapPanel。最后,为单元格类添加一个DataTemplate,以便为每个单元格绘制一个按钮:
<Window.Resources>
<DataTemplate DataType="{x:Type local:Cell}">
<Button Width="32" Height="32" Content="{Binding Text}"/>
</DataTemplate>
</Window.Resources>
<ItemsControl ItemsSource="{Binding Cells}" Width="320" Height="320" HorizontalAlignment="Center" VerticalAlignment="Center">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
这就是你使用WPF的方式。您的逻辑完全存储在视图模型中,并且与视图完全解耦。下面是这段代码所显示的内容,这段代码的灵活性和易更改性应该是不言而喻的:
public MainWindow()
{
InitializeComponent();
this.DataContext = new MainModel();
}
<Window.Resources>
<DataTemplate DataType="{x:Type local:Cell}">
<Button Width="32" Height="32" Content="{Binding Text}"/>
</DataTemplate>
</Window.Resources>
<ItemsControl ItemsSource="{Binding Cells}" Width="320" Height="320" HorizontalAlignment="Center" VerticalAlignment="Center">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>