WPF DataGrid: Blank Row Missing

后端 未结 7 651
春和景丽
春和景丽 2020-11-30 13:49

I am creating a WPF window with a DataGrid, and I want to show the blank \"new item\" row at the bottom of the grid that allows me to add a new item to the grid

相关标签:
7条回答
  • 2020-11-30 14:41

    For me the best way to implement editable asynchronous DataGrid looks like that:

    View Model:

     public class UserTextMainViewModel : ViewModelBase
    { 
        private bool _isBusy;
        public bool IsBusy
        {
            get { return _isBusy; }
            set
            {
                this._isBusy = value;
                OnPropertyChanged();
            }
        }
    
    
    
    
        private bool _isSearchActive;
        private bool _isLoading;
    
    
        private string _searchInput;
        public string SearchInput
        {
            get { return _searchInput; }
            set
            {
                _searchInput = value;
                OnPropertyChanged();
    
                _isSearchActive = !string.IsNullOrEmpty(value);
                ApplySearch();
            }
        }
    
        private ListCollectionView _translationsView;
        public ListCollectionView TranslationsView
        {
            get
            {
                if (_translationsView == null)
                {
                    OnRefreshRequired();
                }
    
                return _translationsView;
            }
            set
            {
                _translationsView = value;
                OnPropertyChanged();
            }
        }
    
    
        private void ApplySearch()
        {
            var view = TranslationsView;
    
            if (view == null) return;
    
            if (!_isSearchActive)
            {
                view.Filter = null;
            }
            else if (view.Filter == null)
            {
                view.Filter = FilterUserText;
            }
            else
            {
                view.Refresh();
            }
        }
    
        private bool FilterUserText(object o)
        {
            if (!_isSearchActive) return true;
    
            var item = (UserTextViewModel)o;
    
            return item.Key.Contains(_searchInput, StringComparison.InvariantCultureIgnoreCase) ||
                   item.Value.Contains(_searchInput, StringComparison.InvariantCultureIgnoreCase);
        }
    
    
    
    
        private ICommand _clearSearchCommand;
        public ICommand ClearSearchCommand
        {
            get
            {
                return _clearSearchCommand ??
                       (_clearSearchCommand =
                        new DelegateCommand((param) =>
                        {
                            this.SearchInput = string.Empty;
    
                        }, (p) => !string.IsNullOrEmpty(this.SearchInput)));
            }
        }
    
        private async void OnRefreshRequired()
        {
            if (_isLoading) return;
    
            _isLoading = true;
            IsBusy = true;
            try
            {
                var result = await LoadDefinitions();
                TranslationsView = new ListCollectionView(result);
            }
            catch (Exception ex)
            {
                //ex.HandleError();//TODO: Needs to create properly error handling
            }
    
            _isLoading = false;
            IsBusy = false;
        }
    
    
        private async Task<IList> LoadDefinitions()
        {
            var translatioViewModels = await Task.Run(() => TranslationRepository.Instance.AllTranslationsCache
            .Select(model => new UserTextViewModel(model)).ToList());
            return translatioViewModels;
        }
    
    
    }
    

    XAML:

    <UserControl x:Class="UCM.WFDesigner.Views.UserTextMainView"
             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:model="clr-namespace:Cellebrite.Diagnostics.Model.Entities;assembly=Cellebrite.Diagnostics.Model"
             xmlns:System="clr-namespace:System;assembly=mscorlib"
             xmlns:converters1="clr-namespace:UCM.Infra.Converters;assembly=UCM.Infra"
             xmlns:core="clr-namespace:UCM.WFDesigner.Core"
             mc:Ignorable="d"
             d:DesignHeight="300"
             d:DesignWidth="300">
    
    
    <DockPanel>
        <StackPanel Orientation="Horizontal"
                    DockPanel.Dock="Top"
                    HorizontalAlignment="Left">
    
    
            <DockPanel>
    
                <TextBlock Text="Search:"
                           DockPanel.Dock="Left"
                           VerticalAlignment="Center"
                           FontWeight="Bold"
                           Margin="0,0,5,0" />
    
                <Button Style="{StaticResource StyleButtonDeleteCommon}"
                        Height="20"
                        Width="20"
                        DockPanel.Dock="Right"
                        ToolTip="Clear Filter"
                        Command="{Binding ClearSearchCommand}" />
    
                <TextBox Text="{Binding SearchInput, UpdateSourceTrigger=PropertyChanged}"
                         Width="500"
                         VerticalContentAlignment="Center"
                         Margin="0,0,2,0"
                         FontSize="13" />
    
            </DockPanel>
        </StackPanel>
        <Grid>
            <DataGrid ItemsSource="{Binding Path=TranslationsView}"
                      AutoGenerateColumns="False"
                      SelectionMode="Single"
                      CanUserAddRows="True">
                <DataGrid.Columns>
                  <!-- your columns definition is here-->
                </DataGrid.Columns>
            </DataGrid>
            <!-- your "busy indicator", that shows to user a message instead of stuck data grid-->
            <Border Visibility="{Binding IsBusy,Converter={converters1:BooleanToSomethingConverter TrueValue='Visible', FalseValue='Collapsed'}}"
                    Background="#50000000">
                <TextBlock Foreground="White"
                           VerticalAlignment="Center"
                           HorizontalAlignment="Center"
                           Text="Loading. . ."
                           FontSize="16" />
            </Border>
        </Grid>
    </DockPanel>
    

    This pattern allows to work with data grid in a quite simple way and code is very simple either. Do not forget to create default constructor for class that represents your data source.

    0 讨论(0)
提交回复
热议问题