向WPF数据网格添加按钮

olqngx59  于 2023-04-13  发布在  其他
关注(0)|答案(4)|浏览(133)

我想在WPF中创建一个DataGrid控件,其中每行的第一个单元格中有一个按钮。单击此按钮将显示RowDetailsTemplate或子行。
如何添加显示/隐藏RowDetailsTemplate的按钮?

cfh9epnr

cfh9epnr1#

首先创建一个DataGridTemplateColumn来包含按钮:

<DataGridTemplateColumn>
  <DataGridTemplateColumn.CellTemplate> 
    <DataTemplate> 
      <Button Click="ShowHideDetails">Details</Button> 
    </DataTemplate> 
  </DataGridTemplateColumn.CellTemplate> 
</DataGridTemplateColumn>

单击按钮后,更新包含DataGridRowDetailsVisibility

void ShowHideDetails(object sender, RoutedEventArgs e)
{
    for (var vis = sender as Visual; vis != null; vis = VisualTreeHelper.GetParent(vis) as Visual)
    if (vis is DataGridRow)
    {
        var row = (DataGridRow)vis;
        row.DetailsVisibility = 
        row.DetailsVisibility == Visibility.Visible ? Visibility.Collapsed : Visibility.Visible;
        break;
    }
}
hzbexzde

hzbexzde2#

看看这个

XAML:

<DataGrid Name="DataGrid1">
    <DataGrid.Columns>
        <DataGridTemplateColumn>
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <Button Click="ChangeText">Show/Hide</Button>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>

方法:

private void ChangeText(object sender, RoutedEventArgs e)
{
    DemoModel model = (sender as Button).DataContext as DemoModel;
    model.DynamicText = (new Random().Next(0, 100).ToString());
}

类别:

class DemoModel : INotifyPropertyChanged
{
    protected String _text;
    public String Text
    {
        get { return _text; }
        set { _text = value; RaisePropertyChanged("Text"); }
    }

    protected String _dynamicText;
    public String DynamicText
    {
        get { return _dynamicText; }
        set { _dynamicText = value; RaisePropertyChanged("DynamicText"); }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    public void RaisePropertyChanged(String propertyName)
    {
        PropertyChangedEventHandler temp = PropertyChanged;
        if (temp != null)
        {
            temp(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

初始化编码:

ObservableCollection<DemoModel> models = new ObservableCollection<DemoModel>();
models.Add(new DemoModel() { Text = "Some Text #1." });
models.Add(new DemoModel() { Text = "Some Text #2." });
models.Add(new DemoModel() { Text = "Some Text #3." });
models.Add(new DemoModel() { Text = "Some Text #4." });
models.Add(new DemoModel() { Text = "Some Text #5." });
DataGrid1.ItemsSource = models;
nimxete2

nimxete23#

XAML

<DataGrid x:Name="dgv_Students" AutoGenerateColumns="False" 
          ItemsSource="{Binding People}" Margin="10,20,10,0" 
          Style="{StaticResource AzureDataGrid}" FontFamily="B Yekan" 
          Background="#FFB9D1BA">
    <DataGrid.Columns>
        <DataGridTemplateColumn>
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <Button Click="RowButton_Click">Text</Button>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
   </DataGrid.Columns>
</DataGrid>

代码隐藏

private IEnumerable<DataGridRow> GetDataGridRowsForButtons(DataGrid grid)
{ 
    //IQueryable
    if (!(grid.ItemsSource is IEnumerable itemsSource)) 
        yield return null;

    foreach (var item in itemsSource)
    {
        var row = grid.ItemContainerGenerator.ContainerFromItem(item) as DataGridRow;
        if (null != row & row.IsSelected) 
           yield return row;
    }
}

private void RowButton_Click(object sender, RoutedEventArgs e)
{
    for (var vis = sender as Visual; vis != null; vis = VisualTreeHelper.GetParent(vis) as Visual)
        if (vis is DataGridRow)
        {
           // var row = (DataGrid)vis;

            var rows = GetDataGridRowsForButtons(dgv_Students);

            string id;
            foreach (DataGridRow dr in rows)
            {
                id = (dr.Item as tbl_student).Identification_code;
                MessageBox.Show(id);
                break;
            }

            break;
        }
}

单击按钮后,该行的ID将返回给您,您可以将其用作按钮名称。

l7wslrjt

l7wslrjt4#

如果你想使用Command,你可以使用下面的例子作为基础。

<DataGridTemplateColumn
Header="Action"
>
<DataGridTemplateColumn.CellTemplate>
    <DataTemplate>
        <Button 
            VerticalAlignment="Top"
            Command="{Binding DataContext.MyCommand, RelativeSource={RelativeSource FindAncestor, 
                AncestorLevel=1, AncestorType={x:Type UserControl}}}" 
            CommandParameter="{Binding .}"
            Content="Delete">                
        </Button>
    </DataTemplate>
</DataGridTemplateColumn.CellTemplate>

检查AncestorTyp是否与ViewModel绑定的父视图匹配。

相关问题