Как получить доступ к родительскому свойству в стиле

В моем Listview элементы данных представлены в виде метки. Я разрабатываю стиль для этой метки и не знаю, как получить доступ к родительскому (ListViewItem) свойству IsSelected.

РЕДАКТИРОВАТЬ - попробовал приведенные ниже предложения, но все равно получил исключение, вот мой полный код:

 <Style x:Key="ListViewItemStyle" TargetType="ListViewItem">
                <Setter Property="SnapsToDevicePixels" Value="true"/>
                <Setter Property="OverridesDefaultStyle" Value="true"/>
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="ListViewItem">
                            <Border BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" Padding="{TemplateBinding Padding}" SnapsToDevicePixels="true">
                                <GridViewRowPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
                            </Border>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
                <Style.Triggers>
                    <Trigger Property="IsSelected" Value="True">
                        <Setter Property="Background" Value="{StaticResource WindowBorderBrush}"/>
                        <Setter Property="Foreground" Value="White"/>
                    </Trigger>
                </Style.Triggers>
            </Style>
            <Style x:Key="GVLabelStyle"
                   BasedOn="{StaticResource LabelStyle}"
                   TargetType="Label">
                <Style.Triggers>
                    <MultiDataTrigger>
                        <MultiDataTrigger.Conditions>
                            <Condition  Property="{Binding Path=IsSelected, RelativeSource={RelativeSource FindAncestor}}" Value="True"/>
                        </MultiDataTrigger.Conditions>            
                        <Setter Property="Foreground" Value="White"/>
                    </MultiDataTrigger>
                </Style.Triggers>
            </Style>

            <DataTemplate x:Key="appTemplate">
                <Label Style="{StaticResource GVLabelStyle}"
                       Content="{Binding ProcessInfo.ProcessName}">
                               </Label>
            </DataTemplate>  

 <ListView Background="Transparent"
                  Name="mainContentHolder"
                  ItemsSource="{Binding}"
                  BorderBrush="Transparent"
                  ItemContainerStyle="{StaticResource ListViewItemStyle}">
                <ListView.View>
                <GridView ColumnHeaderContainerStyle="{StaticResource HeaderStyle}">
                    <GridViewColumn Header="Application" 
                                    CellTemplate="{StaticResource appTemplate}"/>
                    <GridViewColumn Header="Window Title"
                                    CellTemplate="{StaticResource wndTemplate}"
                                    Width="300"/>
                    <GridViewColumn Header="Date"
                                    CellTemplate="{StaticResource dateTemplate}"/>

                </GridView>
            </ListView.View>

        </ListView>

person Marko Devcic    schedule 26.04.2013    source источник


Ответы (3)


Вы должны иметь возможность использовать RelativeSource:

<Condition Property="{Binding Path=IsSelected, RelativeSource={RelativeSource TemplatedParent}}" Value="True" />

РЕДАКТИРОВАТЬ: Попробуйте также использовать MultiDataTrigger вместо MultiTrigger. Проверьте это.

person Community    schedule 26.04.2013
comment
Я пробовал это, но получил это исключение: «Привязка» не может быть установлена ​​​​для свойства «Свойство» типа «Условие». «Привязка» может быть установлена ​​только для свойства DependencyProperty объекта DependencyObject. - person Marko Devcic; 26.04.2013
comment
Я думаю, вы можете использовать RelativeSource={RelativeSource FindAncestor}, чтобы найти точный ListView? - person Fendy; 26.04.2013
comment
При этом я получаю следующее исключение: «Инициализация« System.Windows.Data.RelativeSource »вызвала исключение». Номер строки «38» и позиция строки «37». - person Marko Devcic; 26.04.2013
comment
Хорошо, все заработало... Спасибо... теперь все работает... ‹MultiDataTrigger.Conditions› ‹Condition Binding={Binding RelativeSource={RelativeSource AncestorType={x:Type ListViewItem}}, Path=IsSelected} Value= True/› ‹Condition Binding={Binding RelativeSource={RelativeSource AncestorType={x:Type ListViewItem}}, Path=IsEnabled} Value=True/› ‹/MultiDataTrigger.Conditions› - person Marko Devcic; 26.04.2013

ListView имеет отдельный SelectedItemTemplate. Так что вы могли бы использовать его.

person Anatolii Gabuza    schedule 26.04.2013

Чтобы сэкономить ваше время, публикую синтаксис, который работал у меня и у OP: {Binding RelativeSource={RelativeSource AncestorType={x:Type ParentType}}, Path=ParentProperty}

person user94592    schedule 21.07.2015