How to use binding relativesource in style

那年仲夏 提交于 2019-12-12 04:49:18

问题


Using the default style

<Style TargetType="{x:Type TabItem}"x:Key="HeaderStyleS">
    <Setter Property="Header" Value="{Binding RelativeSource={RelativeSource Self}, 
            Path=Content.DataContext.ViewName}" />
</Style>

It works. But in my case I need to custom the TabItem So I used

<Style TargetType="{x:Type TabItem}" x:Key="HeaderStyle">
<Setter Property="FocusVisualStyle" Value="{x:Null}"/>
<Setter Property="Background" Value="Transparent"/>
<Setter Property="Template">
    <Setter.Value>
        <ControlTemplate TargetType="{x:Type TabItem}">
            <Grid Background="{TemplateBinding Background}" SnapsToDevicePixels="true" Height="23">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="Auto"/>
                    <ColumnDefinition Width="25"/>
                </Grid.ColumnDefinitions>
                <ContentPresenter ContentSource="Header" Margin="10,0,10,0" HorizontalAlignment="Center" VerticalAlignment="Center">
                    <ContentPresenter.Resources>
                        <Style TargetType="TextBlock">
                            <Setter Property="Foreground" Value="{StaticResource Foreground}"/>
                            <Setter Property="Text"  Value="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Content.DataContext.ViewName}"></Setter>
                        </Style>
                    </ContentPresenter.Resources>
                </ContentPresenter>
                <Button Grid.Column="1" Height="15" Width="15" HorizontalAlignment="Center" VerticalAlignment="Center">
                ...
</Style>

The problem now is the Header text is not shown. Any ideas?


回答1:


Try these:

{Binding Path=Content.DataContext.ViewName, RelativeSource={RelativeSource AncestorType={x:Type TabItem}}}

or

{Binding Path=DataContext.ViewName, RelativeSource={RelativeSource AncestorType={x:Type TabItem}}}

or

{Binding Path=ViewName}



来源:https://stackoverflow.com/questions/27572362/how-to-use-binding-relativesource-in-style

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!