WPF 数据网格仅允许用户添加 1 行

问题描述 投票:0回答:1

我有一个 DataGrid,我使用 ObservableCollection 中的一个列表项对其进行了初始化。 我想允许用户完成数据网格的其余部分。 我有 CanUserAddRows=true;我有两个文本框,通过复选框启用/禁用。填写第二行后,除非您双击复选框旁边的单元格之一(不在复选框中),否则它不会添加其他行。 然后,它将所有数字值设置为 0 并清空所有字符串,并将当前行值移动到下一行。 理想情况下,我希望通过单击按钮添加一个新的空行,但会通过按 Enter 键来解决新行。

<Window x:Class="Tourny2.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:Tourny2"
    mc:Ignorable="d"
    Title="Structure Entry" Height="300" Width="804" FontFamily="Verdana" FontSize="16">
<Grid Margin="0,0,0,0">
    <DataGrid x:Name="dataGrid" CanUserAddRows="True" HeadersVisibility="Column" AutoGenerateColumns="False" Background="#FFCEE8E5" VerticalContentAlignment="Center" HorizontalContentAlignment="Center" CanUserSortColumns="False" CanUserReorderColumns="False" FrozenColumnCount="1" ClipToBounds="True">
        <DataGrid.Columns>
            <DataGridTemplateColumn  Header="Levels">
                <DataGridTemplateColumn.CellTemplate >
                    <DataTemplate >
                        <TextBox x:Name="levelEntry"  Width="Auto" Text="{Binding LevelName}"/>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
            <DataGridTemplateColumn Header="Use Antes" >
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <CheckBox x:Name="useAntes" HorizontalAlignment="Right" VerticalAlignment="Bottom" Margin="0,0,5,6" Checked="useAntes_Checked" Unchecked="useAntes_Unchecked" IsChecked="{Binding IsActive}"></CheckBox>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
            <DataGridTemplateColumn x:Name="EnterAntes" Header="Antes">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <TextBox x:Name="antesEntry" Width="Auto" IsEnabled="False" KeyDown="antesEntry_KeyDown" Text="{Binding Antes}" Loaded="antesEntry_Loaded"></TextBox>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
            <DataGridTemplateColumn Header="Small Blind">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <TextBox x:Name="SBEntry" Width="Auto" KeyDown="SBEntry_KeyDown" Text="{Binding SmallBlind}"/>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
            <DataGridTemplateColumn Header="Big Blind">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <TextBox x:Name="BBEntry" Width="Auto" KeyDown="BBEntry_KeyDown" Text="{Binding BigBlind}"/>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
            <DataGridTemplateColumn Header="Level Time">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <TextBox x:Name="levelTimeEntry" Width="Auto" KeyDown="levelTime_KeyDown"  Text="{Binding LevelTime}"/>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
            <DataGridTemplateColumn Header="List Games" >
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <CheckBox x:Name="listGames" HorizontalAlignment="Right" VerticalAlignment="Bottom" Margin="0,0,5,6" Checked="listGames_Checked" Unchecked="listGames_Unchecked" IsChecked="{Binding IsActive}"></CheckBox>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
            <DataGridTemplateColumn Header="Current Game">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <TextBox x:Name="gameEntry" Width="Auto" IsEnabled="False"  Text="{Binding CurrentGame}" Loaded="gameEntry_Loaded"></TextBox>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
        </DataGrid.Columns>
    </DataGrid>
    <Button x:Name="SaveStructure" Content="Save" HorizontalAlignment="Left" Margin="719,0,0,235" VerticalAlignment="Bottom" Width="75" Click="button_Click" Height="35"/>
</Grid>

namespace Tourny2
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
    private TextBox antesEntry;        
    private TextBox gameEntry;

    public Window1()
    {
        InitializeComponent();

        ObservableCollection<Level> levels = new ObservableCollection<Level>();
        levels.Add(new Level() { LevelName = "Level 1", UseAntes = false, SmallBlind = 25, BigBlind = 50, LevelTime = 20, ListGames = false } );
        dataGrid.ItemsSource = levels;
    }

    private void dataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {

    }
    private void antesEntry_Loaded(object sender, RoutedEventArgs e)
    {
        antesEntry = (sender as TextBox);            
    }
    private void gameEntry_Loaded(object sender, RoutedEventArgs e)
    {
        gameEntry = (sender as TextBox);
    }
    private void useAntes_Checked(object sender, RoutedEventArgs e)
    {
        CheckBox c = (sender as CheckBox);
        if (c.IsChecked == true)
        {
            antesEntry.IsEnabled = true;               
        }
    }
    private void listGames_Checked(object sender, RoutedEventArgs e)
    {
        CheckBox c = (sender as CheckBox);
        if (c.IsChecked == true)
        {
            gameEntry.IsEnabled = true;               
        }
    }
    private void useAntes_Unchecked(object sender, RoutedEventArgs e)
    {
        CheckBox c = (sender as CheckBox);
        if (c.IsChecked == false)
        {
            antesEntry.IsEnabled = false;
        }
    }
    private void listGames_Unchecked(object sender, RoutedEventArgs e)
    {
        CheckBox c = (sender as CheckBox);
        if (c.IsChecked == false)
        {
            gameEntry.IsEnabled = false;

        }
    }
    private void antesEntry_KeyDown(object sender, KeyEventArgs e)          //allow only digits (keyboard and numbers pad)
    {                                                                       //tab and backspace to be entered in antes
        int key = (int)e.Key;
        e.Handled = !(key >= 34 && key <= 43 ||
         key >= 74 && key <= 83 || key == 2);
        if (e.Key == Key.Tab)
        {
            e.Handled = false;
        }
    }
    private void SBEntry_KeyDown(object sender, KeyEventArgs e)          //allow only digits (keyboard and numbers pad)
    {                                                                       //tab and backspace to be entered in SB
        int key = (int)e.Key;
        e.Handled = !(key >= 34 && key <= 43 ||
         key >= 74 && key <= 83 || key == 2);
        if(e.Key == Key.Tab|| e.Key == Key.Enter)
        {
            e.Handled = false;
        }           
    }
    private void BBEntry_KeyDown(object sender, KeyEventArgs e)          //allow only digits (keyboard and numbers pad)
    {                                                                       //tab and backspace to be entered in BB
        int key = (int)e.Key;
        e.Handled = !(key >= 34 && key <= 43 ||
         key >= 74 && key <= 83 || key == 2);
        if (e.Key == Key.Tab)
        {
            e.Handled = false;
        }
    }
    private void levelTime_KeyDown(object sender, KeyEventArgs e)          //allow only digits (keyboard and numbers pad)
    {                                                         
                 //tab,and backspace to be entered in Level Time
        int key = (int)e.Key;
        e.Handled = !(key >= 34 && key <= 43 ||
         key >= 74 && key <= 83 || key == 2);
        if (e.Key == Key.Tab||e.Key == Key.Enter)
        {
            e.Handled = false;
        }
    }

    private void button_Click(object sender, RoutedEventArgs e)
    {
        dataGrid.SelectAllCells();
        dataGrid.ClipboardCopyMode = DataGridClipboardCopyMode.ExcludeHeader;
        ApplicationCommands.Copy.Execute(null, dataGrid);
        dataGrid.UnselectAllCells();
        String result = (string)Clipboard.GetData(DataFormats.CommaSeparatedValue);
        Clipboard.Clear();
        using (StreamWriter file = new StreamWriter("..\\TestStructure.csv"))
            {
                file.WriteLine(result);
            }
        }
    }        
}

namespace Tourny2
{
 public class Level : INotifyPropertyChanged
{
    private string levelName = "";                      //declare some fields
    private bool useAntes = false;
    private int antes;                              
    private int smallBlind = 0;
    private int bigBlind = 0;
    private double levelTime = 0;
    private bool listGames = false;
    private string currentGame;

    public string LevelName                             //create properties for the fields       
    {
        get { return this.levelName; }

        set
        {
            if (this.levelName != value)
            {
                this.levelName = value;
                this.NotifyPropertyChanged("LevelName");
            }
        }
    }    
    public bool UseAntes
    {
        get { return this.useAntes; }
        set
        {
            if (this.useAntes != value)
            {
                this.useAntes = value;
                this.NotifyPropertyChanged("UseAntes");
            }
        }
    }
    public int Antes
    {                               
        get { return (int)antes; }
        set
        {
            if (this.antes != value)
            {
                this.antes = value;
                this.NotifyPropertyChanged("Antes");
            }
        }
    }
    public int SmallBlind
    {
        get { return this.smallBlind; }
        set
        {
            if (this.smallBlind != value)
            {
                this.smallBlind = value;
                this.NotifyPropertyChanged("SmallBlind");
            }
        }
    }
    public int BigBlind
    {
        get { return this.bigBlind; }
        set
        {
            if (this.bigBlind != value)
            {
                this.bigBlind = value;
                this.NotifyPropertyChanged("BigBlind");
            }
        }
    }
    public double LevelTime
    {
        get { return this.levelTime; }
        set
        {
            if (this.levelTime != value)
            {
                this.levelTime = value;
                this.NotifyPropertyChanged("LevelTime");
            }
        }
    }
    public bool ListGames
    {
        get { return this.listGames; }
        set
        {
            if (this.listGames != value)
            {
                this.listGames = value;
                this.NotifyPropertyChanged("ListGames");
            }
        }
    }
    public string CurrentGame
    {
        get { return this.currentGame; }
        set
        {
            if (this.currentGame != value)
            {
                this.currentGame = value;
                this.NotifyPropertyChanged("CurrentGame");
            }
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    public void NotifyPropertyChanged(string propName)
    {
        if (this.PropertyChanged != null)
            this.PropertyChanged(this, new PropertyChangedEventArgs(propName));
    }       
    public Level()
    {
        this.levelName = levelName;
        this.useAntes = useAntes;
        this.antes = antes;
        this.smallBlind = smallBlind;
        this.bigBlind = bigBlind;
        this.levelTime = levelTime;
        this.listGames = listGames;
        this.currentGame = currentGame;
    }
c# wpf datagrid row
1个回答
3
投票

您可以通过将以下代码添加到数据网格按键事件来添加空白行。

if(e.Key == Key.Enter)
{
   AddNewRow();
}

现在,实现如下所示的 AddNewRow 方法。

private void AddNewRow()
{
   TestItemList.Add(new TestItem());
   gvTest.ItemsSource = TestItemList;
}

在这里,您只需在数据网格上按 Enter 键即可添加空白行。根据之前的答案,我将 Observable 集合实例声明为全局实例,因此只需添加上述代码即可添加空白行。

希望这对您有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.