Ячейка DataGridTemplateColumn с пользовательским элементом управления не отображается после обновления - PullRequest
0 голосов
/ 20 мая 2018

В моем проекте у меня есть собственный элемент управления LessonCell.Generic.xaml:

 <Style TargetType="{x:Type local:LessonCell}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type local:LessonCell}">
                <Grid Background="{TemplateBinding Background}" Name="LessonGrid">
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition/>
                        <ColumnDefinition/>
                    </Grid.ColumnDefinitions>
                    <Grid.RowDefinitions>
                        <RowDefinition/>
                        <RowDefinition/>
                    </Grid.RowDefinitions>
                    <StackPanel Grid.ColumnSpan="2" Grid.Row="0" VerticalAlignment="Center" HorizontalAlignment="Center">
                        <Label Content="{TemplateBinding SubjectName}"/>
                    </StackPanel>
                    <StackPanel Grid.Column="0" Grid.Row="1" VerticalAlignment="Center" HorizontalAlignment="Left">
                        <Label Content="{TemplateBinding CabinetName}"/>
                    </StackPanel>
                    <StackPanel Grid.Column="1" Grid.Row="1" VerticalAlignment="Center" HorizontalAlignment="Right">
                        <Label Content="{TemplateBinding TeacherName}"/>
                    </StackPanel>
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

LessonCell.cs:

public class LessonCell : Control
{
    static LessonCell()
    {
        DefaultStyleKeyProperty.OverrideMetadata(typeof(LessonCell),
            new FrameworkPropertyMetadata(typeof(LessonCell)));
    }

    public string TeacherName
    {
        get { return (string)GetValue(TeacherNameProperty); }
        set { SetValue(TeacherNameProperty, value); }
    }
    public static readonly DependencyProperty TeacherNameProperty =
        DependencyProperty.Register("TeacherName",
            typeof(string), typeof(LessonCell), new PropertyMetadata(null));

    public string SubjectName
    {
        get { return (string)GetValue(SubjectNameProperty); }
        set { SetValue(SubjectNameProperty, value); }
    }
    public static readonly DependencyProperty SubjectNameProperty =
        DependencyProperty.Register("SubjectName",
            typeof(string), typeof(LessonCell), new PropertyMetadata(null));

    public string CabinetName
    {
        get { return (string)GetValue(CabinetNameProperty); }
        set { SetValue(CabinetNameProperty, value); }
    }
    public static readonly DependencyProperty CabinetNameProperty =
        DependencyProperty.Register("CabinetName",
            typeof(string), typeof(LessonCell), new PropertyMetadata(null));

}

Я использую этот элемент управления в качестве ячейки Datagrid.Для этого, когда я генерирую столбцы таблицы, я устанавливаю ее как CellTemplate:

                DataGridTemplateColumn lessonColumn = new DataGridTemplateColumn();
                lessonColumn.Header = (i + 1) + " урок";
                FrameworkElementFactory lessonCell = new FrameworkElementFactory(typeof(LessonCell));
                lessonCell.SetBinding(BackgroundProperty, new Binding("COLOR_HEX[" + cellNumber + "]")
                {
                    Mode = BindingMode.TwoWay,
                    NotifyOnTargetUpdated = true,
                    UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
                });
                lessonCell.SetBinding(LessonCell.SubjectNameProperty, new Binding("SUBJECT_NAME[" + cellNumber + "]")
                {
                    Mode = BindingMode.TwoWay,
                    NotifyOnTargetUpdated = true,
                    UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
                });
                lessonCell.SetBinding(LessonCell.TeacherNameProperty, new Binding("TEACHER_NAME[" + cellNumber + "]")
                {
                    Mode = BindingMode.TwoWay,
                    NotifyOnTargetUpdated = true,
                    UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
                });
                lessonCell.SetBinding(LessonCell.CabinetNameProperty, new Binding("CABINET_NAME[" + cellNumber + "]")
                {
                    Mode = BindingMode.TwoWay,
                    NotifyOnTargetUpdated = true,
                    UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
                });
                lessonColumn.CellTemplate = new DataTemplate() { VisualTree = lessonCell };
                ScheduleGrid.Columns.Add(lessonColumn);
                multiBindingWidth.Bindings.Add(new Binding("ActualWidth") { Source = lessonColumn });

Строки таблицы хранятся в ObservableCollection с использованием моего пользовательского типа ScheduleString

    private ObservableCollection<ScheduleString> ScheduleStringCollection = new ObservableCollection<ScheduleString>();

    public class ScheduleString
    {
        public int SCHEDVARIANT_ID { get; set; }

        public int CLASS_ID { get; set; }

        public string CLASS_NAME { get; set; }

        public int[] SCHEDSTRING_ID { get; set; }

        public int[] STUDTIME_ID { get; set; }

        public int[] LEARNCLASS_ID { get; set; }

        public int[] TEACHER_ID { get; set; }

        public string[] TEACHER_NAME { get; set; }

        public int[] SUBJECT_ID { get; set; }

        public string[] SUBJECT_NAME { get; set; }

        public int[] CABINET_ID { get; set; }

        public string[] CABINET_NAME { get; set; }

        public string[] COLOR_HEX { get; set; }
    }

Через Itemsource я назначаю эту коллекцию ScheduleGrid.Когда я обновляю коллекцию в своем коде, изменения загружаются в таблицу, но не отображаются в элементе управления my.Но если дважды щелкнуть ячейку с измененными данными, Datagrid отобразит ее.Как это исправить?

Ответы [ 2 ]

0 голосов
/ 22 мая 2018

Я нашел решение своей проблемы.В классе ScheduleString необходимо заменить массивы на ObservableCollection

    public class ScheduleChange
    {
        public int SCHEDVARIANT_ID { get; set; }

        public int CLASS_ID { get; set; }

        public string CLASS_NAME { get; set; }

        public ObservableCollection<int> SCHEDCHANGE_ID { get; set; }

        public ObservableCollection<int> STUDTIME_ID { get; set; }

        public ObservableCollection<int> TEACHER_ID { get; set; }

        public ObservableCollection<string> TEACHER_NAME { get; set; }

        public ObservableCollection<int> SUBJECT_ID { get; set; }

        public ObservableCollection<string> SUBJECT_NAME { get; set; }

        public ObservableCollection<int> CABINET_ID { get; set; }

        public ObservableCollection<string> CABINET_NAME { get; set; }

        public ObservableCollection<int?> GROUP_ID { get; set; }

        public ObservableCollection<DateTime> CHANGE_DATE { get; set; }

        public ObservableCollection<string> COLOR_HEX { get; set; }
    }
0 голосов
/ 21 мая 2018

Попробуйте заменить TemplateBindings обычными привязками в вашем шаблоне:

<Label Content="{Binding SubjectName, RelativeSource={RelativeSource AncestorType=local:LessonCell}}"/>

{TemplateBinding} - это оптимизированная версия привязки, которая имеет некоторые ограничения.

...