XAML 如何根据用户列表在datagrid WPF上自动添加新列?

ymzxtsji  于 2023-04-18  发布在  其他
关注(0)|答案(1)|浏览(143)

我目前正在创建一个软件,我可以添加用户,然后在另一个窗口中计算他们的工作时间。工作时间的窗口有一个组合框,您可以选择特定的用户或所有用户。当用户被选中时,数据网格被编程为只显示所选用户的列。现在我必须实现这样一个事实,即当我选择所有用户时,DataGrid应该自动添加所有用户所需的列。
这是我的XAML格式的datagrid:

<DataGrid
        Name="DgEsportazione"
        AutoGenerateColumns="False"
        IsReadOnly="True"
        ItemsSource="{Binding OreDate, UpdateSourceTrigger=PropertyChanged}"
        BindingGroup="{Binding ListaUtenti}"
        Style="{StaticResource DataGridStyle1}">
        <DataGrid.ItemContainerStyle>
            <Style TargetType="DataGridRow">
                <Style.Triggers>
                    <DataTrigger Binding="{Binding Key.DayOfWeek}" Value="Saturday">
                        <Setter Property="Background" Value="{StaticResource Background}" />
                    </DataTrigger>
                    <DataTrigger Binding="{Binding Key.DayOfWeek}" Value="Sunday">
                        <Setter Property="Background" Value="{StaticResource Background}" />
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </DataGrid.ItemContainerStyle>
        <DataGrid.Columns>
            <DataGridTextColumn
                Width="*"
                MinWidth="100"
                Binding="{Binding Key, ConverterCulture='it-IT', StringFormat=dddd dd/MM}"
                Header="Date"
                IsReadOnly="True" />
            <DataGridTextColumn
                Width="*"
                MinWidth="100"
                Binding="{Binding Value}"
                Header="Working Hours"
                IsReadOnly="True" />
        </DataGrid.Columns>
    </DataGrid>

我试着在互联网上搜索,但没有什么可以帮助我。

cgfeq70w

cgfeq70w1#

由于您没有提供有关场景的任何细节,因此我只能提供一个非常一般的示例。
例如,如果您使用旧的API从数据库读取数据,则可以将其直接读入DataTable
下面的示例显示如何生成一个表,该表由两列“用户名”和“年龄”组成,并填充了两个数据行。有关更多示例,请参见DataTable示例部分。

// If this property is a member of a control e.g. Window, 
// then this property must be a dependency property.
// Otherwise, this property must raise the 'INotifyPropertyChanged.PropertyChanged' event.
public DataTable UserData { get; set; }

var newUserTable = new DataTAble();

/* 1) Define two columns: 'username' of type string and 'Age' of type int */
var usernameColumn = new DataColumn("Username", typeof(string));
newUserTable.Columns.Add(usernameColumn);
var userAge = new DataColumn("Age", typeof(int));
newUserTable.Columns.Add(userAge);

/* 2) Add data (rows) to the table.
*     access columns either by index or by column name. */
DataRow firstRow = newUserTable.NewRow();
firstRow["username"] = "User1";
firstRow["Age"] = "100";
newUserTable.Rows.Add(firstRow);

DataRow secondRow = newUserTable.NewRow();
secondRow[0] = "User2";
secondRow[1] = "200";
newUserTable.Rows.Add(secondRow);

// 3) Assign table to the DataGrid either directly or via data binding (recommended)
this.UserTable = newUserTable;
//this.DataGrid.ItemsSource = newUserTable.DefaultView;

相关问题