D
D
Denis Mashanov2017-11-22 12:20:46
WPF
Denis Mashanov, 2017-11-22 12:20:46

How to populate a table (DataGrid)?

Good evening everyone. In the course of outputting data to the table, I had a problem, namely, there is a class object with data and there are already ready-made columns registered in the XML markup, and when I output, it is not the columns that have already been created that are filled in, but new ones are created with the names of the properties in the table . How to solve this problem, tell me please.

<Window x:Class="Testes.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:Testes"
        xmlns:scm="clr-namespace:System.ComponentModel;assembly=WindowsBase"
        Title="Group, Sort, and Filter Example" Height="575" Width="525">
    <Window.Resources>
        <local:Tasks x:Key="tasks" />
        <CollectionViewSource x:Key="cvsTasks" Source="{StaticResource tasks}" 
                              Filter="CollectionViewSource_Filter"/>
    </Window.Resources>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition />
            <RowDefinition Height="30" />
        </Grid.RowDefinitions>
        <DataGrid x:Name="dataGrid1" 
                  ItemsSource="{Binding Source={StaticResource cvsTasks}}"
                  CanUserAddRows="False">
            <DataGrid.GroupStyle>
                <!-- Стиль для столбцов -->
                <GroupStyle>
                    <GroupStyle.ContainerStyle>
                        <Style TargetType="{x:Type GroupItem}">
                            <Setter Property="Margin" Value="0,0,0,5"/>
                            <Setter Property="Template">
                                <Setter.Value>
                                    <ControlTemplate TargetType="{x:Type GroupItem}">
                                        <Expander IsExpanded="True" Background="#FFA6A6A6" Foreground="#FFEEEEEE" BorderThickness="1,1,1,5" BorderBrush="#FFA6A6A6">
                                            <Expander.Header>
                                                <DockPanel>
                                                    <TextBlock FontWeight="Bold" Text="{Binding Path=Name}" Margin="5,0,0,0" Width="100"/>
                                                    <TextBlock FontWeight="Bold" Text="{Binding Path=ItemCount}"/>
                                                </DockPanel>
                                            </Expander.Header>
                                            <Expander.Content>
                                                <ItemsPresenter />
                                            </Expander.Content>
                                        </Expander>
                                    </ControlTemplate>
                                </Setter.Value>
                            </Setter>
                        </Style>
                    </GroupStyle.ContainerStyle>
                </GroupStyle>
            </DataGrid.GroupStyle>
            <DataGrid.RowStyle>
                <Style TargetType="DataGridRow">
                    <Setter Property="Foreground" Value="Black" />
                    <Setter Property="Background" Value="White" />
                </Style>
            </DataGrid.RowStyle>
            <DataGrid.Columns>
                <DataGridTextColumn Binding="{x:Null}" ClipboardContentBinding="{x:Null}" Header="№1"/>
                <DataGridTextColumn Binding="{x:Null}" ClipboardContentBinding="{x:Null}" Header="№2"/>
                <DataGridTextColumn Binding="{x:Null}" ClipboardContentBinding="{x:Null}" Header="№3"/>
            </DataGrid.Columns>
        </DataGrid>
        <StackPanel Orientation="Horizontal" Grid.Row="1">
            <TextBlock Text=" Filter completed items " VerticalAlignment="Center" />
            <CheckBox x:Name="cbCompleteFilter" VerticalAlignment="Center"
                      Checked="CompleteFilter_Changed" Unchecked="CompleteFilter_Changed" />
            <Button Content="Remove Groups" Margin="10,2,2,2" Click="UngroupButton_Click" />
            <Button Content="Group by Project/Status" Margin="2" Click="GroupButton_Click" />
        </StackPanel>
    </Grid>
</Window>

using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows;
using System.Windows.Data;

namespace Testes
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        ICollectionView cvTasks = null;
        public MainWindow()
        {
            InitializeComponent();
            cvTasks = CollectionViewSource.GetDefaultView(dataGrid1.ItemsSource);
            // Get a reference to the tasks collection.
            Tasks _tasks = (Tasks)this.Resources["tasks"];
            
            // Generate some task data and add it to the task list.
            for (int i = 1; i <= 14; i++)
            {
                _tasks.Add(new Task()
                {
                    ProjectName = "Project " + ((i % 3) + 1).ToString(),
                    TaskName = "Task " + i.ToString(),
                    Name = new Random(i).Next(0,10000)
                });
            }
            _tasks.Add(new Task()
            {
                ProjectName = "",
                TaskName = "",
            });
            cvTasks.GroupDescriptions.Clear();
            cvTasks.GroupDescriptions.Add(new PropertyGroupDescription("ProjectName"));
        }

        /// <summary>
        /// Очистить группу
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UngroupButton_Click(object sender, RoutedEventArgs e)
        {
            if (cvTasks != null)
            {
                cvTasks.GroupDescriptions.Clear();
            }
        }

        /// <summary>
        /// Разделить по группам
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GroupButton_Click(object sender, RoutedEventArgs e)
        {
            if (cvTasks != null && cvTasks.CanGroup == true)
            {
                cvTasks.GroupDescriptions.Clear();
                cvTasks.GroupDescriptions.Add(new PropertyGroupDescription("ProjectName"));
                //cvTasks.GroupDescriptions.Add(new PropertyGroupDescription("TaskName"));
            }
        }

        /// <summary>
        /// Убрать\поставить группировку
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CompleteFilter_Changed(object sender, RoutedEventArgs e)
        {
            CollectionViewSource.GetDefaultView(dataGrid1.ItemsSource).Refresh();
        }
        /// <summary>
        /// Фильтр
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CollectionViewSource_Filter(object sender, FilterEventArgs e)
        {
            Task t = e.Item as Task;
            if (t != null)
            {
                if (cbCompleteFilter.IsChecked == true && t.TaskName.Equals("Task 1"))
                    e.Accepted = false;
                else
                    e.Accepted = true;
            }
        }
    }

    // Task Class
    // Requires using System.ComponentModel;
    public class Task : INotifyPropertyChanged/*, IEditableObject*/
    {
        private string m_ProjectName = string.Empty;
        private string m_TaskName = string.Empty;
        private int m_Name = 0;

        public string ProjectName
        {
            get { return this.m_ProjectName; }
            set
            {
                if (value != this.m_ProjectName)
                {
                    this.m_ProjectName = value;
                    NotifyPropertyChanged("ProjectName");
                }
            }
        }
        public string TaskName
        {
            get { return this.m_TaskName; }
            set
            {
                if (value != this.m_TaskName)
                {
                    this.m_TaskName = value;
                    NotifyPropertyChanged("TaskName");
                }
            }
        }
        public int Name
        {
            get { return this.m_Name; }
            set
            {
                if (value != this.m_Name)
                {
                    this.m_Name = value;
                    NotifyPropertyChanged("TaskName");
                }
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        private void NotifyPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
    public class Tasks : ObservableCollection<Task>
    {
        // Creating the Tasks collection in this way enables data binding from XAML.
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Stanislav Makarov, 2017-11-22
@LoneRay

<DataGrid ...... AutoGenerateColumns="False">
https://msdn.microsoft.com/ru-ru/library/system.wi...
Well, of course, the DataGridTextColumn needs to make normal bindings.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question