WPF - 如何在动态创建的DataGridComboBox中设置默认值?

问题描述 投票:0回答:1

我试图在ComboBox中设置DataGrid的默认值,但无济于事。我正在查看的列是dgProposedDataType,我正在考虑根据值数组将其设置为“Generic”。

<DataGrid x:Name="dgDatabase" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" Height="299" Width="819">
    <DataGrid.Columns>
        <DataGridCheckBoxColumn x:Name="dgIsTested" />
        <DataGridComboBoxColumn x:Name="dgProposedDataType" />
    </DataGrid.Columns>
</DataGrid>

窗口加载功能(WPF应用程序打开并加载后立即加载)

private void OnLoaded(object sender, RoutedEventArgs e)
{
    //Connect to SQL Database
    connObj = new SqlConnection(connection);
    cmdObj = new SqlCommand("SELECT DISTINCT TABLE_NAME, COLUMN_NAME, DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS", connObj);
    daAdapObj = new SqlDataAdapter(cmdObj);
    daAdapObj.Fill(dsObj, "Table");
    String[] myArray = { "Generic", "Number", "Date" };

    dgDatabase.ItemsSource = dsObj.Tables["Table"].DefaultView;
    dgProposedDataType.ItemsSource = myArray;
}
c# wpf
1个回答
0
投票

你需要将DataGridComboBoxColumn绑定到DataTable的列:

<DataGridComboBoxColumn x:Name="dgProposedDataType" SelectedItemBinding="{Binding YourColumn}" />

然后,您可以为DataTable中的所有行设置此列的值:

private void OnLoaded(object sender, RoutedEventArgs e)
{
    //Connect to SQL Database
    connObj = new SqlConnection(connection);
    cmdObj = new SqlCommand("SELECT DISTINCT TABLE_NAME, COLUMN_NAME, DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS", connObj);
    daAdapObj = new SqlDataAdapter(cmdObj);
    daAdapObj.Fill(dsObj, "Table");

    String[] myArray = { "Generic", "Number", "Date" };
    dgProposedDataType.ItemsSource = myArray;

    var table = dsObj.Tables["Table"];
    //add a new column to hold the selected value
    table.Columns.Add("YourColumn");
    //set the default value of this column
    foreach (DataRow row in dt.Rows)
        row["YourColumn"] = myArray[0];

    table.Columns["YourColumn"].DefaultValue = myArray[0]; //= Generic

    dgDatabase.ItemsSource = table.DefaultView;
}
© www.soinside.com 2019 - 2024. All rights reserved.