Проверка записи столбца в динамически создаваемой DataGrid - компилируется, но ничего не отображается - PullRequest
0 голосов
/ 02 декабря 2018

Следуя многим примерам, я создал динамически созданную DataGrid из коллекции.Когда я включаю компонент DataValidation для одного из столбцов, следующий код компилируется, но ничего не отображается.Без компонента проверки это работает.Я был бы очень признателен, если бы опытный участник мог указать на мою ошибку.

Большое спасибо.

i.konuk

XAML:

<Window x:Class="SimpleGridX.MainWindow"
        xmlns:local="clr-namespace:SimpleGridX"
        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"

        mc:Ignorable="d"

        Title="MainWindow" Height="450" Width="800">

    <Grid>

        <ScrollViewer HorizontalAlignment="Left" Margin="10,10,0,0"
                      VerticalAlignment="Top" Width="497" Height="299" 
                      HorizontalScrollBarVisibility="Auto"
                      VerticalScrollBarVisibility="Auto" >

            <DataGrid Name="dgSimpleX" AutoGenerateColumns="True" 
                      SelectionUnit="FullRow" SelectionMode="Extended" 
                      CanUserReorderColumns="False" CanUserAddRows="True">

                <DataGridTextColumn Header="Age">
                    <DataGridTextColumn.Binding>
                        <Binding Path="[Age]">
                            <Binding.ValidationRules>
                                <local:MyValidationRule />
                            </Binding.ValidationRules>
                        </Binding>
                    </DataGridTextColumn.Binding>
                </DataGridTextColumn>

            </DataGrid>

        </ScrollViewer>

    </Grid>

</Window>

Код окна:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

using System.ComponentModel;

namespace SimpleGridX
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            // Create an instance of the PersonCollection class
            PersonCollection people =
                new PersonCollection();

            InitializeComponent();
            dgSimpleX.SelectionUnit = DataGridSelectionUnit.CellOrRowHeader;
            dgSimpleX.ItemsSource = people;
            dgSimpleX.Items.SortDescriptions.Add(new SortDescription("FirstName", ListSortDirection.Descending));

        }
    }
}

Класс объекта:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.ComponentModel;
using System.Windows.Controls;
using System.Globalization;

namespace SimpleGridX
{
    class Person : INotifyPropertyChanged
    {
        private string firstName;
        private string lastName;
        private float age;
        private string occupation;

        // Each property calls the OnPropertyChanged method
        // when its value changed, and each property that 
        // affects the Person's Description, also calls the 
        // OnPropertyChanged method for the Description property.

        public string FirstName
        {
            get
            {
                return firstName;
            }
            set
            {
                if (firstName != value)
                {
                    firstName = value;
                    OnPropertyChanged("FirstName");
                    OnPropertyChanged("Description");
                }
            }
        }

        public string LastName
        {
            get
            {
                return lastName;
            }
            set
            {
                if (this.lastName != value)
                {
                    this.lastName = value;
                    OnPropertyChanged("LastName");
                    OnPropertyChanged("Description");
                }
            }
        }

        public float Age
        {
            get
            {
                return age;
            }
            set
            {
                if (this.age != value)
                {
                    this.age = value;
                    OnPropertyChanged("Age");
                    OnPropertyChanged("Description");
                }
            }
        }

        public string Occupation
        {
            get { return occupation; }
            set
            {
                if (this.occupation != value)
                {
                    this.occupation = value;
                    OnPropertyChanged("Occupation");
                    OnPropertyChanged("Description");
                }
            }
        }

        // The Description property is read-only,
        // and is composed of the values of the
        // other properties.
        public string Description
        {
            get
            {
                return string.Format("{0} {1}, {2} ({3})",
                                     firstName, lastName, age, occupation);
            }
        }

        // The ToString returns the Description,
        // so that it is displayed by default when 
        // the Person object is a binding source.
        public override string ToString()
        {
            return Description;
        }

        #region INotifyPropertyChanged Members

        /// Implement INotifyPropertyChanged to notify the binding
        /// targets when the values of properties change.
        public event PropertyChangedEventHandler PropertyChanged;

        private void OnPropertyChanged(
            string propertyName)
        {
            if (this.PropertyChanged != null)
            {
                // Raise the PropertyChanged event
                this.PropertyChanged(
                    this,
                    new PropertyChangedEventArgs(
                        propertyName));
            }
        }

        #endregion
    }

    #region ValidationRule

    public class MyValidationRule : ValidationRule
    {
        public override ValidationResult Validate(object value, CultureInfo cultureInfo)
        {
            float myage = (float)0.0;

            try
            {
                if (((string)value).Length > 0)
                {
                    myage = (float)Decimal.Parse((string)value, NumberStyles.Any, cultureInfo);
                }
            }
            catch
            {
                return new ValidationResult(false, "Illegal ccharacters");
            }

            if ((myage < (float)0.0) || (myage > (float)75.0))
            {
                return new ValidationResult(false, "Not in range");
            }
            else
            {
                return new ValidationResult(true, null);
            }

        }


    }

    #endregion

}

Коллекция:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections.ObjectModel;

namespace SimpleGridX
{
    class PersonCollection : ObservableCollection<Person>
    {
        public PersonCollection()
        {
            // Load the collection with dummy data
            //
            Add(new Person()
            {
                FirstName = "Elin",
                LastName = "Binkles",
                Age = 26,
                Occupation = "Professional"
            });

            Add(new Person()
            {
                FirstName = "Samuel",
                LastName = "Bourts",
                Age = 28,
                Occupation = "Engineer"
            });

            Add(new Person()
            {
                FirstName = "Alan",
                LastName = "Jonesy",
                Age = 37,
                Occupation = "Engineer"
            });

            Add(new Person()
            {
                FirstName = "Sam",
                LastName = "Nobles",
                Age = 25,
                Occupation = "Engineer"
            });
        }

    }

}

1 Ответ

0 голосов
/ 02 декабря 2018

Свойство Age должно быть связано без квадратных скобок.Также.Он будет привязан к двум столбцам, если вы оставите autogenerate true.Редактировать:

Также.Вам нужны любые столбцы внутри коллекции столбцов.То, что у вас там, выдает ошибку, когда я пытаюсь это сделать, потому что он пытается превратить ваш столбец возраста в элемент, а затем код пытается установить itemssource.

        <DataGrid.Columns>
            <DataGridTextColumn Header="Age"> 
              ……
          </DataGrid.Columns>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...