繁体   English   中英

没有 XAML 的 WPF 绑定

[英]WPF Binding Without XAML

我有一个带有“网格窗口”的 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分配给矩形的描边。 每当(假定的 SolidColorBrush) _GridColor的 Color 属性发生变化时,它都会影响所有矩形。

public SolidColorBrush _GridColor { get; } = new SolidColorBrush(); 
...

var rect = new Rectangle
{
    Name = $"rec{(i + 1).ToString("00")}{(j + 1).ToString("00")}",
    Height = squareSize,
    Width = squareSize,
    Fill = _ColorOff,
    Stroke = _GridColor // here
};

Grid.SetColumn(rect, i);
Grid.SetRow(rect, (y - j - 1));
grdBattleGrid.Children.Add(rect);

通过为_GridColor Brush 的Color属性赋值来更改矩形描边:

_GridColor.Color = Colors.Red;

您只需要为Window设置一次DataContext ,而不是为每个Rectangle

是否从INotifyPropertyChanged接口Binding您自己的视图模型类? 链接到 MS 文档

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM