如何动态地使用List填充wpf datagrid列文本?

时间:2011-08-23 09:48:31

标签: wpf datagrid textwrapping

我有一个像xaml:

<GroupBox Header="groupBox1" Height="174" HorizontalAlignment="Left" Margin="36,38,0,0" Name="groupBox1" VerticalAlignment="Top" Width="285">
        <ScrollViewer HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto">
            <Grid x:Name="caseListGrid">
            </Grid>
        </ScrollViewer>
</GroupBox>

在.cs文件中我有一个函数:

private void LoadDataGrid()
{
    caseElementList = new List<CaseElement>();
    caseElementList.Clear();

    //add 1st element
    caseElementList.Add(new CaseElement
    {
        CaseName = "First Name",
        Description = "Recently I came across the need to customize the look of the standard message box in the application. To do this I’ve decided to create a new class named WPFMessageBox"
    });

    //add second
    caseElementList.Add(new CaseElement
    {
        CaseName = "Second Name",
        Description = "Recently I came across the need to customize the look of the standard message box in the application. To do this I’ve decided to create a new class named WPFMessageBox"
    });

    caseElementList.Add(new CaseElement
    {
        CaseName = "Third Name",
        Description = "Recently I came across the need to customize the look of the standard message box in the application. To do this I’ve decided to create a new class named WPFMessageBox"
    });


    DataGrid dGrid = new DataGrid();                        
    dGrid.AutoGenerateColumns = true;            
    dGrid.ItemsSource = caseElementList;
    this.caseListGrid.Children.Add(dGrid);
}

这里我在函数中创建了一个自定义案例对象列表。然后我将列表分配给datagrid(在创建datagrid之后)。

但因为我没有在数据网格中添加样式..而且文本非常大。所以, 它正在滚动视图中扩展。

但我想用文字包装来显示它们。那么,谁能给我任何解决方案?

我发现使用textblock可以解决。但我无法弄清楚我如何在该数据网格中添加文本块,因为我正在动态创建它.. !!

1 个答案:

答案 0 :(得分:0)

解决方案1:不要AutoGenerateColumns并自己指定列。

解决方案2:订阅AutoGeneratingColumn事件并将列更改为包装内容(例如,使用列的ElementStyle属性)。