使用XAML创建DataGrid并在WPF中绑定

时间:2017-02-25 17:28:04

标签: c# wpf binding datagrid

我正在创建一个包含多行和多列的数据网格。我已经在XAML中成功创建了datagrid,并在代码中创建了列,但发现我有一些限制。我需要更好地理解绑定,并希望转换我的代码以使用绑定在XAML中创建datagrid。列正在重复。这是我之前的代码:

之前的XAML:

<DataGrid Name="dtGrid" Loaded="GridLoaded" VirtualizingPanel.IsVirtualizing="False" Height="365" Width="558" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="54,74,0,0" BorderThickness="1" BorderBrush="Black">
        <DataGrid.Resources>
            <Style TargetType="{x:Type DataGridCell}">
                <Style.Triggers>
                    <Trigger Property="DataGridCell.IsSelected" Value="True">
                        <Setter Property="Background" Value="#FF9DF3D6" />
                        <Setter Property="Foreground" Value="#000000" />
                    </Trigger>
                </Style.Triggers>
                <EventSetter Event="PreviewMouseLeftButtonDown" Handler="DataGridCell_PreviewMouseLeftButtonDown" />
                <EventSetter Event="LostFocus" Handler="DataGridCell_OnCellLostFocus" />
            </Style>
        </DataGrid.Resources>
    </DataGrid>

XAML更改:

<DataGrid HeadersVisibility="Column" Name="dtGrid" Loaded="GridLoaded" VirtualizingPanel.IsVirtualizing="False" Height="365" Width="558" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="54,74,0,0" BorderThickness="1" BorderBrush="Black">
        <DataGrid.Columns>
            <DataGridTextColumn Header="Field" Binding="{Binding Field}" />
            <DataGridTextColumn Header="Size" Binding="{Binding Size, Mode=TwoWay}" />
            <DataGridCheckBoxColumn Header="Right Justify" Binding="{Binding RightJustify, Mode=TwoWay}" />
            <DataGridCheckBoxColumn Header="Left Justify" Binding="{Binding LeftJustify, Mode=TwoWay}" />
            <DataGridCheckBoxColumn Header="Left Zero Fill" Binding="{Binding LeftZeroFill, Mode=TwoWay}" />
            <DataGridCheckBoxColumn Header="Right Zero Fill" Binding="{Binding RightZeroFill, Mode=TwoWay}" />
        </DataGrid.Columns>
        <DataGrid.Resources>
            <Style TargetType="{x:Type DataGridCell}">
                <Style.Triggers>
                    <Trigger Property="DataGridCell.IsSelected" Value="True">
                        <Setter Property="Background" Value="#FF9DF3D6" />
                        <Setter Property="Foreground" Value="#000000" />
                    </Trigger>
                </Style.Triggers>
                <EventSetter Event="PreviewMouseLeftButtonDown" Handler="DataGridCell_PreviewMouseLeftButtonDown" />
                <EventSetter Event="LostFocus" Handler="DataGridCell_OnCellLostFocus" />
            </Style>
        </DataGrid.Resources>
    </DataGrid>

C#:

private void DisplayFieldLengths(string strFLFileName, string[,] strFieldInfo)
    {
        int intDisplayCnt = 0;
        string strData, strFieldSize = "";
        bool blnRightJustify, blnLeftJustify, blnLeftZeroFill, blnRightZeroFill;


        blnRightJustify = false;
        blnLeftJustify = false;
        blnLeftZeroFill = false;
        blnRightZeroFill = false;
        intTotalRowSize = 0;
        lblFLInfo.Content = "File: " + strFLFileName;
        DataTable dtGridData = new DataTable();
        dtGridData.Columns.Add("Field", typeof(string));
        dtGridData.Columns.Add("Size", typeof(string));
        dtGridData.Columns.Add("RightJustify", typeof(bool));
        dtGridData.Columns.Add("LeftJustify", typeof(bool));
        dtGridData.Columns.Add("LeftZeroFill", typeof(bool));
        dtGridData.Columns.Add("RightZeroFill", typeof(bool));

        try
        {
            int intArraySize = strFieldInfo.GetLength(0);

            for (intDisplayCnt = 0; intDisplayCnt < strFieldInfo.GetLength(0); intDisplayCnt++)
            {
                strFieldSize = strFieldInfo[intDisplayCnt, 1];
                Int32 intStringNumValue;
                bool blnValueIsNumber = Int32.TryParse(strFieldSize, out intStringNumValue);

                if (strFieldSize != null && !(string.IsNullOrEmpty(strFieldSize)) && blnValueIsNumber)
                {
                    if (strFieldSize.Length == 1)
                    {
                        strFieldSize = "0" + strFieldSize;
                    }

                    if (string.IsNullOrEmpty(strFieldInfo[intDisplayCnt, 2]))
                    {
                        blnRightJustify = false;
                    }
                    else
                    {
                        blnRightJustify = Convert.ToBoolean(strFieldInfo[intDisplayCnt, 2]);
                    }

                    if (string.IsNullOrEmpty(strFieldInfo[intDisplayCnt, 3]))
                    {
                        blnLeftJustify = false;
                    }
                    else
                    {
                        blnLeftJustify = Convert.ToBoolean(strFieldInfo[intDisplayCnt, 3]);
                    }

                    if (string.IsNullOrEmpty(strFieldInfo[intDisplayCnt, 4]))
                    {
                        blnLeftZeroFill = false;
                    }
                    else
                    {
                        blnLeftZeroFill = Convert.ToBoolean(strFieldInfo[intDisplayCnt, 4]);
                    }

                    if (string.IsNullOrEmpty(strFieldInfo[intDisplayCnt, 5]))
                    {
                        blnRightZeroFill = false;
                    }
                    else
                    {
                        blnRightZeroFill = Convert.ToBoolean(strFieldInfo[intDisplayCnt, 5]);
                    }


                    strData = strFieldInfo[intDisplayCnt, 0] + "|" + strFieldSize + "|" + blnRightJustify + "|"
                        + blnLeftJustify + "|" + blnLeftZeroFill + "|" + blnRightZeroFill;
                    dtGridData.Rows.Add(strData.Split('|'));
                }
                else
                {
                    strFieldSize = "01";
                }
            }

            dtGrid.ItemsSource = dtGridData.DefaultView;
            dtGrid.AutoGeneratingColumn += dtGrid_AutoGeneratingColumn;
            intTotalRowSize = GetFLTotalFileSize(strFieldInfo);
            lblRowSize.Content = " Total row length: " + intTotalRowSize;
            intTotalNumberColumns = strFieldInfo.GetLength(0);
            lblNumFields.Content = "Number of fields: " + intTotalNumberColumns;
        }
        catch (Exception e)
        {
            string strMsg;

            strMsg = "FixedLengths->DisplayFieldLengths, error '" + e.Message + "' has occurred.";
            System.Windows.MessageBox.Show(strMsg);
        }
    }

1 个答案:

答案 0 :(得分:0)

默认情况下,DataGrid的

AutoGenerateColumns属性为true。因此,当您在代码中使用dtGrid.ItemsSource = dtGridData.DefaultView;时,它将根据DataTable的列生成列。

但是,您也在手动添加列,在Xaml的这些行中添加:

<DataGrid.Columns>
     <DataGridTextColumn Header="Field" Binding="{Binding Field}" />
      ....
</DataGrid.Columns>

只需删除它们,一切都会好的。

当然,您也可以设置AutoGenerateColumns="false",然后您将再次看到DataTable中每列的一列。