我在我的View xaml代码中设置了一个Grid.它由一个填充64个矩形和32个图像的网格组成.我有一个模型类,我想将一些属性绑定到XMAL-opjects属性的图像.ChessBoardViewModel.cs中的代码:
foreach (ChessPiece Piece in ChessPieces)
{
Image Img = ChessBoard.FindName(Piece.Name) as Image;
Binding RowBinding = new Binding("Row");
RowBinding.Source = Piece;
Img.SetBinding(Grid.RowProperty, RowBinding);
Binding ColumnBinding = new Binding("Column");
ColumnBinding.Source = Piece;
Img.SetBinding(Grid.ColumnProperty, ColumnBinding);
}
Run Code Online (Sandbox Code Playgroud)
Chessboard是包含所有图像的Grid的名称.
我的计划是应该将图像绑定到每个实例行和列值,以确定它们在游戏中的位置.
问题是,即使我已经包含了Views命名空间,我也无法出于某种原因访问XAML对象.
编辑:
好的,这是我的代码,以及我如何计划现在这样做:
<Grid x:Name="ChessBoard">
<Rectangle x:Name="A1" Fill="Black" Grid.Column="1" />
...
...
<Image x:Name="BlkRook1" Source="../Data/BlkRook.png" Grid.Row="{Binding ChessBoardViewModel.ChessPieces[0].Row}" Grid.Column="{Binding ChessPieces[0].Column}"/>
...
</Grid>
Run Code Online (Sandbox Code Playgroud)
和Viewmodel包含我的ChessPieces列表
ChessPieces.Add(new BlkRook() { Name = "BlkRook1", Row = 0, Column = 0 });
Run Code Online (Sandbox Code Playgroud)
我想将XAML图像Grid.Row和Grid.Column属性绑定到我的对象的正确实例.但似乎无法找到实现它的方法.
WPF是一种以数据为中心的语言,或者至少在以这种方式使用它时效果最好.我的意思是我们操纵数据对象,而不是UI对象.因此,您永远不需要访问UI'board'控件,而是Binding
访问该控件的集合并操作集合中的项目.
作为一个简短的例子,你可以Bind
收集64个项目到a UniformGrid
,其中32个有一些字段使它们显示为"空".例如,您可以string
为每个项目定义一个属性,以定义要显示的图像,并且空白方块可能在string
那里为空.
然后Grid
,您可以简单地将集合中的相关项目移动到新位置,而不是尝试将UI项目从一个位置移动到另一个位置...例如,如果您想将一块板块向上移动一块正方形,然后你将它移动到收集开始的8个项目,并移动那里有8个位置的空白项目.