【发布时间】:2018-12-11 20:04:08
【问题描述】:
我有一个带有“网格窗口”的 WPF 应用程序。此窗口没有添加 XAML。我创建了一个网格(列和行),然后在每个 C# 中放置一个矩形。 这使我可以在设置“笔画”的位置创建一个网格,并在设置“填充”时在网格上显示位置。
整个网格设置相同,也就是说,如果网格的一部分是红色的,那么整个网格都是红色的。目前,我通过遍历所有矩形并设置“Stroke”属性来设置网格。这工作正常,但与大多数其他操作相比似乎非常慢。我想将 stroke 属性绑定到 C# 中的一个变量(除非迭代是一种合理的处理方式)。
我在这里查看了很多问题,但大多数都想使用 XAML。我下面的代码基于Binding without XAML [WPF]。没有错误,网格永远不会出现。
// put a rectangle in each square
for (int i = 0; i < x; i++) // for each column
{
for (int j = 0; j < y; j++) // for each row
{
// create a new rectangle with name, height, width, and starting color (transparent)
var rect = new Rectangle()
{
Name = $"rec{(i + 1).ToString("00")}{(j + 1).ToString("00")}", //column 5 row 2 -> rec0502
Height = squareSize,
Width = squareSize,
Fill = _ColorOff
};
// create the binding
var binder = new Binding
{
Source = _GridColor, // Brush that is updated on color change
Path = new PropertyPath("Stroke")
};
// apply the binding to the rectangle
rect.SetBinding(Rectangle.StrokeProperty, binder);
rect.DataContext = binder;
// place the rectangle
Grid.SetColumn(rect, i); // current column
Grid.SetRow(rect, (y - j - 1)); // same row but from the bottom (puts point 0,0 at bottom left)
// add the rectangle to the grid
grdBattleGrid.Children.Add(rect);
}
}
即使迭代没问题,我仍然想知道我做错了什么。
编辑:颜色名称是从单独窗口上的 ComboBox 中选择的。这会更新用户设置,进而引发我的“网格窗口”订阅的事件。在遍历矩形之前,我将名称转换为 SolidColorBrush。
【问题讨论】:
-
为了创建一个更新其目标属性的绑定,您需要一个带有属性更改通知的源属性。我猜
_GridColor不是。也许添加一个带有更改通知的GridStroke属性(例如实现 INotifyPropertyChanged)到包含您正在显示的代码的类。然后将 Binding 写为var binding = new Binding { Source = this, Path = new PropertyPath("GridStroke") };。不需要设置 Rectangle 的 DataContext。 -
填充和网格颜色(通常)是不同的颜色。如果我将它绑定到 Color 属性,它将是相同的颜色,对吗?
标签: c# wpf data-binding wpf-controls