簡體   English   中英

每個WPF DataGrid列中的按鈕

[英]Button in every WPF DataGrid Column

我想向每個wpf datagrid列添加一個按鈕。 我的列是自動生成的,所以我在xaml中沒有列的定義。 如何使用列模板進行此操作,以便我擁有列標題和右側的按鈕。

編輯:

<DataGrid ItemsSource="{Binding User.myDataTable}" AutoGenerateColumns="True">
        <DataGrid.ColumnHeaderStyle>
            <Style TargetType="DataGridColumnHeader">
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate>
                            <StackPanel Orientation="Horizontal">
                                <TextBlock Text="Here I want my ColumnName" />
                                <Button Content="Button"/>
                            </StackPanel>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Style>
        </DataGrid.ColumnHeaderStyle>
    </DataGrid>

User.myDataTable填充在模型中,並且工作正常。

您可以通過使用樣式來做到這一點:

<DataGrid>
    <DataGrid.ColumnHeaderStyle>
        <Style TargetType="DataGridColumnHeader">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate>
                        <StackPanel Orientation="Horizontal">
                            <TextBlock Text="{Binding ColumnName}" />
                            <Button Content="Button" />
                        </StackPanel>
                    </ControlTemplate>
                 </Setter.Value>
             </Setter>
         </Style>
     </DataGrid.ColumnHeaderStyle>
 <DataGrid>
 use the below code:-

    DataGridTemplateColumn templateColumn = new DataGridTemplateColumn();

    FrameworkElementFactory HeaderStackpanel = new    FrameworkElementFactory(typeof(StackPanel));
    FrameworkElementFactory btn = new FrameworkElementFactory(typeof(Button));
    // Set the property for  Button

    btn.SetValue(Button.MarginProperty, new Thickness(-50, 0, 0, 0));
    btn.AddHandler(Button.ClickEvent, new RoutedEventHandler(BtnClick));
     // Set the Text Value to the buttons

    btn.SetValue(Button.ContentProperty, strEdit);

   // Append the Edit Button

   HeaderStackpanel.AppendChild(btn);
   DataTemplate headerTemplate = new DataTemplate();
   headerTemplate.VisualTree = HeaderStackpanel;

   templateColumn.HeaderTemplate = headerTemplate;                     

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM