简体   繁体   中英

Set style of extended TreeViewItem based on an extended property value

I have extended the TreeViewItem class to allow me to store extra data within a tree view item. I would like to be able to set the style of the treeview item based on the value of one of the extended properties I have added.

So far I have:

namespace GX3GUIControls
{
    public class GX3TreeViewItem : TreeViewItem
    {

        public bool Archived { get; set; }
        public object Value { get; set; }
    }
}

<src:GX3ClientPlugin.Resources>
        <Style TargetType="{x:Type Controls:GX3TreeViewItem}">
            <Style.Triggers>
                <DataTrigger Archived="True">
                    <Setter Property="Background" Value="Gray" />
                    <Setter Property="FontStyle" Value="Italic" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </src:GX3ClientPlugin.Resources>

But I get the error - Error 1 The property 'Archived' was not found in type 'DataTrigger

DataTrigger has no Archived property, but you can bind your Achived-property to it via the Binding property like so <DataTrigger Binding="{Binding Path=Archived}" Value="True">

To notify your view if the Achived property changes, you could either:

1.Implement the INotifyPropertyChanged Interface in your GX3TreeViewItem -class: public class GX3TreeViewItem : TreeViewItem, INotifyPropertyChanged , create a method which raises the PropertyChanged Event:

private void PropertyChanged(string prop)
{
   if( PropertyChanged != null )
   {
      PropertyChanged(this, new PropertyChangedEventArgs(prop);
   }
}

and place this method in the setter of your property:

private bool _achived;
public bool Achived
{
   get
   {
      return _achived;
   }
   set
   {
      _achived = value;
      PropertyChanged("Achived");
   }
}

2.Or make your property a DependencyProperty .

Honestly it seems like you're doing it wrong. Those properties should be on your data.

You can do something like this,

Style="{Binding Path=Archived, Converter={StaticResource GetStyle}}"

GetStyle is an IValueConverter, no need to extend TreeView imo.

This is not the correct way to implement this. you should take a look at the MVVM Pattern .

Your UI is not the proper place to "store extra data". UI is UI and data is data. This is the worst mistake done by people coming from a winforms or otherwise non-WPF background, using a wrong approach and a wrong mindset in WPF.

This will either not work (because the ItemContainerGenerator of the TreeView knows nothing about your class, or require extra work in overriding the default behavior of such class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM