WPF DataGrid: Blank Row Missing

北城余情 提交于 2019-11-27 16:06:44

Vincent Sibal posted an article describing what is required for adding new rows to a DataGrid. There are quite a few possibilities, and most of this depends on the type of collection you're using for SelectedProject.Tasks.

I would recommend making sure that "Tasks" is not a read only collection, and that it supports one of the required interfaces (mentioned in the previous link) to allow new items to be added correctly with DataGrid.

You must also have to have a default constructor on the type in the collection.

Finally got back to this one. I am not going to change the accepted answer (green checkmark), but here is the cause of the problem:

My View Model wraps domain classes to provide infrastructure needed by WPF. I wrote a CodeProject article on the wrap method I use, which includes a collection class that has two type parameters:

VmCollection<VM, DM>

where DM is a wrapped domain class, and DM is the WPF class that wraps it.

It truns out that, for some weird reason, having the second type parameter in the collection class causes the WPF DataGrid to become uneditable. The fix is to eliminate the second type parameter.

Can't say why this works, only that it does. Hope it helps somebody else down the road.

In my opinion this is a bug in the DataGrid. Mike Blandford's link helped me to finally realize what the problem is: The DataGrid does not recognize the type of the rows until it has a real object bound. The edit row does not appear b/c the data grid doesn't know the column types. You would think that binding a strongly typed collection would work, but it does not.

To expand upon Mike Blandford's answer, you must first assign the empty collection and then add and remove a row. For example,

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        // data binding
        dataGridUsers.ItemsSource = GetMembershipUsers();
        EntRefUserDataSet.EntRefUserDataTable dt = (EntRefUserDataSet.EntRefUserDataTable)dataGridUsers.ItemsSource;
        // hack to force edit row to appear for empty collections
        if (dt.Rows.Count == 0)
        {
            dt.AddEntRefUserRow("", "", false, false);
            dt.Rows[0].Delete();
        }
    }

Add an empty item to your ItemsSource and then remove it. You may have to set CanUserAddRows back to true after doing this. I read this solution here: (Posts by Jarrey and Rick Roen)

I had this problem when I set the ItemsSource to a DataTable's DefaultView and the view was empty. The columns were defined though so it should have been able to get them. Heh.

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.

This happned to me , i forgot to new up the instance and it was nightmare for me . once i created an instance of the collection in onviewloaded it was solved.

`observablecollection<T> _newvariable = new observablecollection<T>();`

this solved my problem. hope it may help others

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!