【问题标题】:Programmatically Binding Button Properties to an Indexer Object以编程方式将按钮属性绑定到索引器对象
【发布时间】:2018-12-17 12:42:41
【问题描述】:

我正在尝试将以编程方式生成的按钮的内容属性绑定到索引器对象。 我的索引器对象如下所示:

internal class Indexer
{
    private int[,] cells;//values from 0 to gridSize^2

    public int this[int x, int y]
    {
        get { return cells[x, y]; }
    }

    public Indexer(int gridSize)
    {
        cells = new int[gridSize, gridSize];

        FillCells(gridSize);
    }

    private void FillCells(int size)
    {
        for (int i = 0; i < size; i++)
        {
            for (int j = 0; j < size; j++)
            {
                cells[i, j] = i * size + j;
            }
        }
    }
}

按钮和绑定在两个嵌套的 for 循环中创建,并添加到统一的网格中。 作为测试,我将所有 Button.Content 属性绑定到一个单一属性,如下所示:

                Button myButton = new Button()
                mazeWindow.XAML_Grid.Children.Add(myButton);

                Binding myBinding = new Binding();
                myBinding.Source = this;
                myBinding.Path = new PropertyPath("GridSize");
                myButton.SetBinding(Button.ContentProperty, myBinding);

这似乎工作正常。但是,我一直无法弄清楚如何修改绑定代码,以便将按钮内容绑定到索引器中的各个单元格。 由于 PropertyPath 构造函数可以用路径参数重载,我假设我可以传递我的索引器对象 和两个整数作为参数来设置绑定,如下所示:

                myBinding.Source = this.indexerObject;
                myBinding.Path = new PropertyPath("Indexer",i,j);

但这会导致 BindingExpression 路径错误:在 'object' ''Indexer' 上找不到 'Indexer' 属性

我认为索引器一定有一些我不理解的地方(以前从未使用过它们),或者我解决这个问题的方法存在某种缺陷。

【问题讨论】:

    标签: c# binding indexer


    【解决方案1】:

    您必须使用旧的好字符串格式化程序在路径字符串中指定索引(插值字符串同样好):

    for (int i = 0; i < 10; i++)
        for (int j = 0; j < 10; j++)
        {
            var myButton = new Button();
            grid.Children.Add(myButton);
            myButton.SetValue(Grid.ColumnProperty, i);
            myButton.SetValue(Grid.RowProperty, j);
            Binding myBinding = new Binding($"GridSize[{i},{j}]") { Source = this };
            myButton.SetBinding(Button.ContentProperty, myBinding);
        }
    

    我使用了 10x10 的网格,其中填充了按钮,将相应数量的行/列定义添加到 xaml。

    【讨论】:

      【解决方案2】:

      回答我自己的问题。 原来我的索引器类实际上缺少一行:

          [IndexerName("SomeIndexerName")]
          public int this[int x, int y]
          {
              get { return cells[x, y]; }
          }
      

      之后我删除了额外的 PropertyPath 参数并简单地使用了:

                      myBinding.Source = this.indexerObject;
                      myBinding.Path = new PropertyPath($"SomeIndexerName[{i},{j}]");  
      

      它成功了!

      【讨论】:

        猜你喜欢
        • 2011-03-17
        • 2016-08-01
        • 1970-01-01
        • 2014-08-04
        • 2012-11-13
        • 1970-01-01
        • 1970-01-01
        • 2023-04-01
        • 2018-02-14
        相关资源
        最近更新 更多