将WPF DataGrid绑定到一维数组

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


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>

然后,将DataContextof设置MyGrid为Cylinder该类的实例。窗口随DataGrid控件一起显示,但是我有2个问题:


将DataGrid填充了正确的数据,但在一个奇怪的方式。我得到一个3x3的网格,第一行全为4,第二行全为5,第三行全为6。

当我尝试编辑9个单元格中的任何一个时,出现一个异常:

双向绑定需要Path或XPath


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


叮当猫咪
浏览 602回答 1
1回答

弑天下

您有一个一维数组,那么如何将其绑定到3列?想想看,它就DataGrid像是二维数组的显示,列是x轴,行是y轴。因此,一维数组必须位于一列的行中。编辑为了表示您在注释中提到的更复杂的类型,可以使用直接将其DataTable绑定DataGrid到数据(仅用于非常简单的项目),List<>如果绑定到业务对象则可以使用更好的类型。这是一个例子:更改类以具有所需的三个属性(为它们提供比本示例更有意义的名称):public class Cylinder {&nbsp; &nbsp; public float Vector1 = { get; set; };&nbsp; &nbsp; public float Vector2 = { get; set; };&nbsp; &nbsp; public float Vector3 = { get; set; };}现在您可以将您DataGrid直接绑定到此类进行测试,但是在实际应用程序中,数据来自某个来源(例如数据库),您可以创建此类的列表:var cylinders = new List<Cylinder>();然后用来自数据库的数据填充它:foreach(var row in myTable) {&nbsp; &nbsp; var c = new Cylinder();&nbsp; &nbsp; c.Vector1 = 4;&nbsp; &nbsp; c.Vector2 = 5;&nbsp; &nbsp; c.Vector3 = 6;&nbsp; &nbsp; cylinders.Add(c);}现在,您可以将绑定DataGrid到cylinders。网格将具有三列,分别代表Cylinder该类的三个属性,以及与您所拥有的一样多的行myTable。
打开App,查看更多内容
随时随地看视频慕课网APP