Создаю игру Альтернативные Крестики-нолики (81 игровая ячейка) на WPF, столкнулся с проблемой генерации ячеек через Canvas на игровом поле, генерирую их через код. Чтобы разместить ячейки внутри мини-Canvas наследовал свой класс SmallGameArea от Canvas, и добавил поле Cells, но их заполнить не удалось, т.к. возникает исключение Null Reference при создании ячеек внутри поля
Просьба подсказать решение данной проблемы, потому что вариант у меня только костыльный, т.к. мне нужно отталкиваться от размерности мини-поля, придется добавить еще одну ссылку на SmallGameArea со значениями Width и Height вот так:
this._smallGameArea =
new SmallGameArea
{
Width = (this._bigAreaCanvas.Width / 3) - 3.0,
Height = (this._bigAreaCanvas.Height / 3) - 3.0
};
this._smallGameArea =
new SmallGameArea
{
Name = "smallField_" + smallArea._coordinateX.ToString() + "_" + smallArea._coordinateY.ToString(),
Width = (this._bigAreaCanvas.Width / 3) - 3.0,
Height = (this._bigAreaCanvas.Height / 3) - 3.0,
Background = (Brush)bc.ConvertFrom("#a4ba8f"),
Cells = FillPlayingCells(this._smallGameArea)
};
Код MainWindow.xaml
<Grid x:Name="mainGrid" Width="800" Height="800" HorizontalAlignment="Center" VerticalAlignment="Center">
<Canvas x:Name="_bigAreaCanvas" Width="800" Height="800" Margin="5">
</Canvas>
</Grid>
Код MainWindow.cs
public MainWindow()
{
InitializeComponent();
FillPlayingArea();
}
private void FillPlayingArea()
{
// Задаем размерность игрового поля
var size = 3;
// Очищаем игровое поле от элементов
this._bigAreaCanvas.Children.Clear();
// Заполняем Backend данными
BigArea bigArea = new BigArea();
var bc = new BrushConverter();
double bigAreaWidth = (this._bigAreaCanvas.Width / 3) - 3.0;
double bigAreaHeight = (this._bigAreaCanvas.Height / 3) - 3.0;
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
var smallArea = ((SmallArea)bigArea.playField[i, j]);
this._smallGameArea =
new SmallGameArea
{
Name = "smallField_" + smallArea._coordinateX.ToString() + "_" + smallArea._coordinateY.ToString(),
Width = (this._bigAreaCanvas.Width / 3) - 3.0,
Height = (this._bigAreaCanvas.Height / 3) - 3.0,
Background = (Brush)bc.ConvertFrom("#a4ba8f"),
Cells = FillPlayingCells(this._smallGameArea)
};
this._bigAreaCanvas.Children.Add(this._smallGameArea);
// Размещаем элементы внутри основного Canvas
Canvas.SetLeft(this._smallGameArea, i * this._bigAreaCanvas.Width / size - 2.0);
Canvas.SetTop(this._smallGameArea, j * this._bigAreaCanvas.Height / size - 2.0);
}
}
}
private List<GameCell> FillPlayingCells (SmallGameArea smallGameArea) // object[,] playCells, double smallCanvasWidth, double smallCanvasHeight
{
List<GameCell> gameCells = new List<GameCell>();
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
var bc = new BrushConverter();
gameCells.Add(
new GameCell
{
Name = "cell_" + i.ToString() + "_" + j.ToString(),
Width = smallGameArea.Width / 3 - 2.0,
Height = smallGameArea.Height / 3 - 2.0,
Background = (Brush)bc.ConvertFrom("#73a9ff"),
coordX = i,
coordY = j
}
);
}
}
return gameCells;
}
Код класса SmallGameArea.cs
public class SmallGameArea : Canvas
{
private List<GameCell> _cells;
public List<GameCell> Cells
{
get { return _cells; }
set
{
_cells = value;
foreach (var cell in _cells)
{
this.Children.Add(cell);
// Размещаем игровые ячейки внутри каждого мини-поля Canvas
Canvas.SetLeft(cell, cell.coordX * this.Height / 3 - 5.0);
Canvas.SetTop(cell, cell.coordY * this.Width / 3 - 5.0);
}
}
}
Просьба подсказать по дополнительной проблеме с оповещением ViewModel через форму, реализовал отправку активного объекта ячейки в VM, но только по статичным координатам(BigGameArea.MiniAreasList[1].SmallAreaCellsList[1].Coordinates), как можно отслеживать координаты. которые выбрал пользователь на форме и динамически подставлять в код Xaml чтобы передать в VM? Или подход неправильный?
Код XAML
<ItemsControl Grid.Row="1" Margin="5" ItemsSource="{Binding BigGameArea.MiniAreasList}" HorizontalAlignment ="Center" VerticalAlignment="Center">
<ItemsControl.ItemTemplate>
<DataTemplate>
<ItemsControl ItemsSource="{Binding SmallAreaCellsList}">
<ItemsControl.Style>
<Style TargetType="ItemsControl">
<Setter Property="BorderBrush" Value="LightBlue"/>
<Setter Property="BorderThickness" Value="3"/>
<Setter Property="Margin" Value="8"/>
<Style.Triggers>
<DataTrigger Binding="{Binding IsActive}" Value="True">
<Setter Property="BorderBrush" Value="IndianRed"/>
</DataTrigger>
<DataTrigger Binding="{Binding IsActive}" Value="False">
<Setter Property="BorderThickness" Value="0"/>
<!--<Setter Property="IsEnabled" Value="False"/>-->
</DataTrigger>
</Style.Triggers>
</Style>
</ItemsControl.Style>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button CommandParameter="{Binding Path=BigGameArea.MiniAreasList[1].SmallAreaCellsList[1]}" Command="{Binding DoTurnCommandVm}" Cursor="Pen">
<Button.DataContext>
<vm:MainViewModel/>
</Button.DataContext>
<Button.Style>
<Style TargetType="Button">
<Setter Property="Background" Value="White"/>
<Setter Property="Width" Value="50"/>
<Setter Property="Height" Value="50"/>
<Setter Property="Margin" Value="2"/>
<Setter Property="BorderBrush" Value="LightBlue"/>
<Setter Property="Background" Value="White"/>
<Style.Triggers>
<!--<DataTrigger Binding="{Binding CellState}" Value="Empty">
<Setter Property="Content" Value=""/>
</DataTrigger>-->
<DataTrigger Binding="{Binding CellState}" Value="Cross">
<Setter Property="Content" Value="{StaticResource CrossImg}"/>
</DataTrigger>
<DataTrigger Binding="{Binding CellState}" Value="Zero">
<Setter Property="Content" Value="{StaticResource ZeroImg}"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Button.Style>
</Button>
</DataTemplate>
</ItemsControl.ItemTemplate>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid Rows="3" Columns="3" Margin="8"></UniformGrid>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
</DataTemplate>
</ItemsControl.ItemTemplate>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel Orientation="Horizontal"></WrapPanel>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
Код MainViewModel.cs
public class MainViewModel
{
public BigGameAreaModel BigGameArea { get; set; }
public MainViewModel()
{
// Создаем игровое поле размерностью 3 х 3
BigGameArea = new BigGameAreaModel(3);
}
private ICommand _doTurnVm;
public ICommand DoTurnCommandVm => _doTurnVm ??= new RelayCommand(parameter =>
{
var activeCell = (CellModel)parameter;
});
}
Выкладываю ссылку на рабочий проект: https://github.com/Gosha94/TicTacToeGame/tree/master/TicTacToeGame.WPF
area[10,15].State = 1
, и на экране появится крестик, сам. В этом и есть смысл привязки данных - писать простой код. Если смогу, попробую написать простой пример.[][]
, можно обертку с двумерным индексатором прикрутить[,]
для удобства.