在WPF中向DataGrid添加按钮

时间:2013-05-23 19:06:59

标签: wpf datagrid

我有DataGrid

<DataGrid x:Name="dgTimeline" GridLinesVisibility="Horizontal" AutoGenerateColumns="False" CanUserAddRows="False" CanUserResizeColumns="false" 
        IsReadOnly="True" VerticalAlignment="Stretch" CanUserReorderColumns="False" CanUserSortColumns="False" Height="Auto" SelectionMode="Single" Focusable="False" Margin="0,293,0,0" CanUserResizeRows="False" GotFocus="dgTimeline_GotFocus">

    <DataGrid.CellStyle>
        <Style TargetType="DataGridCell">
            <Setter Property="BorderThickness" Value="0" />
            <Setter Property="Foreground" Value="Black" />
            <Style.Triggers>
                <Trigger Property="IsSelected" Value="True">
                    <Setter Property="Background" Value="{x:Null}" />
                    <Setter Property="BorderBrush" Value="{x:Null}" />
                 </Trigger>
            </Style.Triggers>
        </Style>
    </DataGrid.CellStyle>
</DataGrid>

它的列和行都是动态生成的。如何向第一列的所有行添加按钮?我试过了:

<DataGrid.Columns>
    <DataGridTemplateColumn>
        <DataGridTemplateColumn.CellTemplate>
            <DataTemplate>
                <Button>Show/Hide</Button>
            </DataTemplate>
        </DataGridTemplateColumn.CellTemplate>
    </DataGridTemplateColumn>
</DataGrid.Columns>

以下是我添加第一列的方法:

DataGridTextColumn dgTextCol = new DataGridTextColumn();
dgTextCol.Header = "Events / Time";
dgTextCol.Width = 150;
dgTextCol.Binding = new Binding("Name");
dgTimeline.Columns.Add(dgTextCol);

然后我添加项目:

public class TimeScale
{
    public string Name { get; set; }
}

TimeScale temp = new TimeScale { Name = "foo" };

dgTimeline.Items.Add(temp);

foo将出现在第一列。

如何在第一列的行中设置按钮,我该怎么办?

1 个答案:

答案 0 :(得分:0)

我能够解决它:

DataGridTemplateColumn dgc = new DataGridTemplateColumn();
DataTemplate dtm = new DataTemplate();

FrameworkElementFactory btnReset = new FrameworkElementFactory(typeof(Button));
btnReset.SetValue(Button.ContentProperty, new Binding("Name"));
btnReset.SetValue(Button.ToolTipProperty, "Restore Selected Row");

dtm.VisualTree = btnReset;
dgc.Header = "";
dgc.CellTemplate = dtm;
dgTimeline.Columns.Add(dgc);