Создал массив прямоугольников в canvas.
Хочу изменить координаты элементов массива при изменении размеров холста.
Что я делаю не так?
Код xaml:
<Window x:Class="WpfAppNetFrameworkCanvasRecArrayTest.MainWindow"
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:WpfAppNetFrameworkCanvasRecArrayTest"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid Background="Cyan">
<Canvas x:Name="canvas" Background="LightCyan" Margin="10">
<Rectangle x:Name="rec" Width="20" Height="20" Fill="Red"/>
</Canvas>
</Grid>
c#:
int canWidth, canHeight;
int X = 500, Y = 200;
int recSize = 20;
Rectangle[] recArr = new Rectangle[6];
public MainWindow()
{
InitializeComponent();
Loaded += MainWindow_Loaded;
canvas.SizeChanged += Canvas_SizeChanged;
}
private void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
Canvas.SetLeft(rec, X);
Canvas.SetTop(rec, Y);
createRecArray();
}
private void Canvas_SizeChanged(object sender, SizeChangedEventArgs e)
{
UpdatePositionCan(e);
}
void UpdatePositionCan(SizeChangedEventArgs e)
{
var point = e.NewSize;
var newPos = point;
canWidth = (int)newPos.Width;
canHeight = (int)newPos.Height;
int x = canWidth - recSize;
int y = canHeight - recSize;
if(canWidth < X + recSize)
{
Canvas.SetLeft(rec, x);
X = x;
}
if(canHeight < Y + recSize)
{
Canvas.SetTop(rec, y);
Y = y;
}
Canvas.SetTop(recArr[2], y); // Эта строка выдает ошибку !!!
}
void createRecArray()
{
int x, y;
Color color;
for(int i = 0; i < 6; i++)
{
x = canWidth / 2 + i * recSize - 6 * recSize;
y = canHeight - recSize*2;
color = numToColor(i);
recArr[i] = new Rectangle();
canvas.Children.Add(recArr[i]);
Canvas.SetLeft(recArr[i], x);
Canvas.SetTop(recArr[i], y);
recArr[i].Width = recSize;
recArr[i].Height = recSize;
recArr[i].Fill = new SolidColorBrush(color);
}
}
Текс ошибки:
System.ArgumentNullException HResult=0x80004003 Message=Значение не может быть неопределенным. Имя параметра: element Source=PresentationFramework StackTrace: at System.Windows.Controls.Canvas.SetTop(UIElement element, Double length) at WpfAppNetFrameworkCanvasRecArrayTest.MainWindow.UpdatePositionCan(SizeChangedEventArgs e) in D:\Programming\WPF\TESTs\WpfAppNetFrameworkCanvasRecArrayTest\MainWindow.xaml.cs:line 76