c# - 如何使数据网格在控件中看到编辑?

标签 c# wpf xaml datagrid

我有一个用于填充数据网格的用户控件。

我希望用户能够通过编辑底部的空行来添加项目。 (这就是我使用数据网格而不是项目控件的原因)但是,除非用户单击控件的背景,否则数据网格不会意识到最后一个项目已被编辑。我希望在用户对控件公开的属性进行更改时添加新项目。

控件的XAML:

<UserControl x:Class="ControlTest.MyControl"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         xmlns:local="clr-namespace:ControlTest"
         mc:Ignorable="d" 
         d:DesignHeight="50" d:DesignWidth="300"
         DataContext="{Binding Path=., Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
         >
<StackPanel Orientation="Vertical">
        <TextBox Text="{Binding Path=p1, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
           Width="300"
           Height="30"
           VerticalAlignment="Center"/>
    <ComboBox ItemsSource="{Binding Path=DropDownValues,
              RelativeSource={RelativeSource Mode=FindAncestor,
                AncestorType=local:MyControl}}"
              SelectedItem="{Binding Path=p2, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
              Height="30"/>
    </StackPanel>
</UserControl>

CS:

public partial class MyControl : UserControl
{
    private static readonly DependencyProperty DropDownValuesProperty =
        DependencyProperty.Register(
        "DropDownValues", 
        typeof(List<String>),
        typeof(MyControl),
        new FrameworkPropertyMetadata(new List<String>()
        ));
    public List<String> DropDownValues
    {
        get
        {
            return (List<String>)GetValue(DropDownValuesProperty);
        }
        set
        {
            SetValue(DropDownValuesProperty, value);
        }
    }

    public MyControl()
    {
        InitializeComponent();
    }        
}

数据网格 XAML

    <DataGrid 
        AutoGenerateColumns="False" 
        ItemsSource="{Binding objs, Mode=TwoWay}" 
        HeadersVisibility="None"
        Margin="0,0,0.4,0"
        CanUserAddRows="True"
        >
        <DataGrid.ItemsPanel>
            <ItemsPanelTemplate>
                <StackPanel Orientation="Horizontal"/>
            </ItemsPanelTemplate>
        </DataGrid.ItemsPanel>
        <DataGrid.Columns>
            <DataGridTemplateColumn Width="300">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate DataType="local:Measure">
                        <local:MyControl 
                            DataContext="{Binding ., Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
                            DropDownValues=
                        "{Binding DataContext.list, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}"
                            Width="300"
                        />
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
        </DataGrid.Columns>
    </DataGrid>

我能做到这一点吗,和/或有更好的方法吗?

最佳答案

我想向您推荐一种不同的方法:

设置CanUserAddRows=false在您的 DataGrid 上,然后手动将行添加到 ObservableCollection<Something>您的 DataGrid 绑定(bind)到的。

如果您仍然对您遵循的方法感兴趣:

在您的 xaml 文件中:

<DataGrid x:Name="myDataGrid" CellEditEnding="DataGrid_CellEditEnding" .....>
    <!--Some Code-->
</DataGrid>

然后在代码隐藏中:

private void DataGrid_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
{
    myDataGrid.CommitEdit();
}

如果您有什么不明白的,请随时提问。

更新

如果您采用相同的方法:

在您的 DataGrid 的开始编辑事件中,您可以尝试:

private void DataGrid_BeginningEdit(object sender, DataGridBeginningEditEventArgs e)
{
    if ((selectedRow as DataGridRow).Item.ToString() != "{NewItemPlaceholder}")
    {
        //Here you can add the code to add new item. I don't know how but you should figure out a way
    }
}

注意:上面提到的代码没有经过测试。

我也建议你:

不使用 DataGrid。而是使用列表框。因为,您正在尝试添加一些数据。此时,您永远不需要排序、搜索和列重新排序等功能。在这种情况下,ListBox 很有用,因为它是比数据网格更轻量级的控件。我这里有一个样本:https://drive.google.com/open?id=0B5WyqSALui0bTXFGZWxQUWVRdkU

关于c# - 如何使数据网格在控件中看到编辑?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37701578/

相关文章:

c# - 卸载 Application Insights nuget 包是否安全?

c# - 挂接到事件时 C# 中的 COMException

使用正确的 .Begin(this,true) 时,WPF Storyboard非交互式错误

c# - 如何使用 MVVM 更新 Datagrid?

c# - WPF 数据绑定(bind)有问题

C#:如何在基类的构造函数中使用派生类的 const 变量

c# - 为什么我的仪表板 View 不显示?

c# - WPF-XAML 与 C# : Which (if any) has the best performance for creating UI

wpf - 动态添加行/列到网格

javascript - 如何从 asp.net 中的 javascript 调用代码隐藏函数?