Цвет задает c древовидных элементов на основе свойства объекта - PullRequest
0 голосов
/ 17 февраля 2020

У меня есть объект SampleTypeRepresentation, который имеет логическое свойство "IsNew". Учитывая приведенное ниже древовидное представление, как мне покрасить объекты SampleTypeRepresentation с IsNew = true?

Спасибо за любую помощь по этому вопросу. Я знаю, что мне нужно реализовать какой-то стиль триггера, но я обнаружил, что ресурсы в сети немного сбивают с толку и до сих пор не повезло.

        <TreeView x:Name="tvSTR" ItemsSource="{Binding SampleTypeRepresentations}" Height="445"
                  SelectedItemChanged="tvSTR_SelectedItemChanged" MouseDoubleClick="tvSTR_DoubleClick">
        <TreeView.Resources>
                <HierarchicalDataTemplate DataType="{x:Type local:SampleTypeRepresentations}" ItemsSource="{Binding Path=SampleTypeRepresentation}">
                    <TextBlock Text="{Binding Name}"/>
                    <HierarchicalDataTemplate.ItemTemplate>
                        <HierarchicalDataTemplate DataType="{x:Type local:SampleTypeRepresentation}" ItemsSource="{Binding Path=ChildSampleTypeRepresentations.SampleTypeRepresentation}">
                            <TextBlock Text="{Binding Name}"/>
                        </HierarchicalDataTemplate>
                    </HierarchicalDataTemplate.ItemTemplate>
                </HierarchicalDataTemplate>
            </TreeView.Resources>
        </TreeView>

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

[XmlRoot(ElementName = "SampleTypeRepresentations", Namespace = "http://www.hilllaboratories.com/ns/clientrequestoptions")]
public class SampleTypeRepresentations
{
    [XmlElement(ElementName = "SampleTypeRepresentation", Namespace = "http://www.hilllaboratories.com/ns/clientrequestoptions")]
    public List<SampleTypeRepresentation> SampleTypeRepresentation { get; set; }
    [XmlAttribute(AttributeName = "ID")]
    public string ID { get; set; }
    [XmlAttribute(AttributeName = "Name")]
    public string Name { get; set; }
    [XmlAttribute(AttributeName = "ReportingGroup")]
    public string ReportingGroup { get; set; }
}

[XmlRoot(ElementName = "ChildSampleTypeRepresentations", Namespace = "http://www.hilllaboratories.com/ns/clientrequestoptions")]
public class ChildSampleTypeRepresentations : INotifyPropertyChanged
{
    private ObservableCollection<SampleTypeRepresentation> sampleTypeRepresentation;

    [XmlElement(ElementName = "SampleTypeRepresentation", Namespace = "http://www.hilllaboratories.com/ns/clientrequestoptions")]
    public ObservableCollection<SampleTypeRepresentation> SampleTypeRepresentation { get => sampleTypeRepresentation;
        set
        {
            sampleTypeRepresentation = value;
            NotifyPropertyChanged();
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}


[XmlRoot(ElementName = "SampleTypeRepresentation", Namespace = "http://www.hilllaboratories.com/ns/clientrequestoptions")]
public class SampleTypeRepresentation : INotifyPropertyChanged
{
    //Controls highlighting in UI
    [XmlIgnore]
    public bool IsNew = false;

    private ChildSampleTypeRepresentations childSampleTypeRepresentations;
    private string name;

    [XmlElement(ElementName = "Name", Namespace = "http://www.hilllaboratories.com/ns/clientrequestoptions")]
    public string Name { get => name;
        set
        {
            if (name == value)
            {
                return;
            }

            name = value;
            NotifyPropertyChanged();
        }
     }


    [XmlElement(ElementName = "SampleTypeInfo", Namespace = "http://www.hilllaboratories.com/ns/clientrequestoptions")]
    public SampleTypeInfo SampleTypeInfo { get; set; }
    [XmlElement(ElementName = "ChildSampleTypeRepresentations", Namespace = "http://www.hilllaboratories.com/ns/clientrequestoptions")]
    public ChildSampleTypeRepresentations ChildSampleTypeRepresentations
    {
        get => childSampleTypeRepresentations;
        set
        {
            if (childSampleTypeRepresentations == value)
            {
                return;
            }

            childSampleTypeRepresentations = value;
            NotifyPropertyChanged();
        }
    }
    public event PropertyChangedEventHandler PropertyChanged;

    private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

1 Ответ

0 голосов
/ 17 февраля 2020

Я изменил выборку до чуть менее насыщенной (удаленные атрибуты и т. Д. c). Вот что не так с вашим HierarchicalDataTemplate:

<HierarchicalDataTemplate DataType="{x:Type local:Manufacturer}" ItemsSource="{Binding Path=Models}">
    <TextBlock>
        <TextBlock.Text>
            <MultiBinding StringFormat="{}{0} &lt;from: {1}&gt;">
                <Binding Path="Name" />
                <Binding Path="HeadQuarters" />
            </MultiBinding>
        </TextBlock.Text>
    </TextBlock>
</HierarchicalDataTemplate>

<HierarchicalDataTemplate DataType="{x:Type local:Model}" ItemsSource="{Binding Path=Variants}">
    <TextBlock>
        <TextBlock.Text>
            <MultiBinding StringFormat="{}{0} costs {1}">
                <Binding Path="Name" />
                <Binding Path="Price" />
            </MultiBinding>
        </TextBlock.Text>
        <TextBlock.Style>
            <Style TargetType="TextBlock">
                <Style.Triggers>
                    <DataTrigger Binding="{Binding IsNew}" Value="true">
                        <Setter Property="Foreground" Value="Green"/>
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </TextBlock.Style>
    </TextBlock>
</HierarchicalDataTemplate>

<DataTemplate DataType="{x:Type local:Variant}">
    <TextBlock Text="{Binding Name}"/>
</DataTemplate>

Не знаю, почему ваша Иерархия содержится друг в друге.

Для ясности вот моя модель:

public class Manufacturer
    {
        public string Name { get; set; }
        public string HeadQuarters { get; set; }
        public List<Model> Models { get; set; }
    }

    public class Model
    {
        public string Name { get; set; }
        public string Price { get; set; }
        public bool IsNew { get; set; }
        public List<Variant> Variants { get; set; }
    }

    public class Variant
    {
        public string Name { get; set; }
        public string FuelType { get; set; }
    }

Это вывод. Обратите внимание, что RAV4 помечен IsNew = true, поэтому его цвет зеленый, как определено в Trigger

AnswerImage

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...