繁体   English   中英

将WPF DataGrid绑定到一维数组

[英]Bind WPF DataGrid to one-dimensional array

我有一个简单的一维数组:

class Cylinder {
    private float[] vector = new float[3] {4,5,6};
    public float[] Vector = { get; set; }
}

在我的XAML中,我创建了带有一些简单绑定的DataGrid

<Grid x:Name="MyGrid>
    <DataGrid ItemsSource="{Binding Vector, Mode=TwoWay}">
        <DataGrid.Columns>
            <DataGridTextColumn Binding="{Binding Path=.}"/>
            <DataGridTextColumn Binding="{Binding Path=.}"/>
            <DataGridTextColumn Binding="{Binding Path=.}"/>
        </DataGrid.Columns>
    </DataGrid>
<Grid>

然后,将MyGridDataContext设置为Cylinder类的实例。 窗口显示与DataGrid控件,但我有2个问题:

  1. DataGrid填充了正确的数据,但是方式很奇怪。 我得到一个3x3的网格,第一行全为'4',第二行全为'5',第三行全为'6'。
  2. 当我尝试编辑9个单元格中的任何一个时,出现异常:

双向绑定需要Path或XPath

我想我可以只制作三个单独的TextBox控件,但是我认为这样会更优雅。

您有一个一维数组,那么如何将其绑定到3列? 想想看, DataGrid就像是二维数组的显示,列是x轴,行是y轴。 因此,一维数组必须位于一列的行中。

编辑为了表示您在注释中提到的更复杂的类型,如果将DataGrid直接绑定到数据(仅用于非常简单的项目),或者如果绑定到业务对象,则可以使用更好的List<>来使用DataTable 这是一个例子:

更改类以具有所需的三个属性(为它们提供比本示例更有意义的名称):

public class Cylinder {
    public float Vector1 = { get; set; };
    public float Vector2 = { get; set; };
    public float Vector3 = { get; set; };
}

现在,您可以将DataGrid直接绑定到此类进行测试,但是在实际应用程序中,数据来自某个来源(例如数据库),您可以创建此类的列表:

var cylinders = new List<Cylinder>();

然后用来自数据库的数据填充它:

foreach(var row in myTable) {
    var c = new Cylinder();
    c.Vector1 = 4;
    c.Vector2 = 5;
    c.Vector3 = 6;
    cylinders.Add(c);
}

现在,您可以将DataGrid绑定到cylinders 网格将具有三列,分别代表Cylinder类的三个属性,以及与myTable行一样多的行。

暂无
暂无

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

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