ControlTemplates的Datacontext

Gif*_*fen 5 wpf datacontext binding controltemplate

ControlTemplate如何处理datacontext?

使用以下模板

<ControlTemplate x:Key="ToolbarButtonHover" TargetType="Button">
    <Grid Name="backgroundGrid">
        <Image Source="{DynamicResource ResourceKey=Img}" Width="{TemplateBinding Width}" Height="{TemplateBinding Height}"></Image>
    </Grid>
    <ControlTemplate.Triggers>
        <DataTrigger Binding="{Binding Path=DataContext.ToolSelected, RelativeSource={RelativeSource TemplatedParent}}" Value="Unlink">
            <Setter TargetName="backgroundGrid" Property="Background" Value="Red" />
        </DataTrigger>
    </ControlTemplate.Triggers>
</ControlTemplate>
Run Code Online (Sandbox Code Playgroud)

与控制

<Button Content="Button" 
        Template="{StaticResource ResourceKey=ToolbarButtonHover}" 
        Height="24" Width="24" Background="Red">
    <Button.Resources>
        <ImageSource x:Key="Img">Resources/Icons/toolSelect.png</ImageSource>
    </Button.Resources>
</Button>
Run Code Online (Sandbox Code Playgroud)

但这并没有使背景变红.我已经验证了ToolbarViewModel属性的值ToolSelected实际上是通过在控件<Label Content="{Binding ToolSelected}"/>旁边使用Unlink 来实现的.所以我认为问题是模板没有使用正确的DataContext,但我不确定.这就是我向你求助的原因.

控制在于自定义用户控件,并ToolbarViewModel设置为背景的这一切,就像这样.

<UserControl.DataContext>
    <local:ToolboxView/>
</UserControl.DataContext>
Run Code Online (Sandbox Code Playgroud)

dko*_*ozl 4

尝试从那时删除RelativeSourceDataTrigger.Binding应该在 current 中工作DataContext

<DataTrigger Binding="{Binding ToolSelected}" Value="Unlink">
   <Setter TargetName="backgroundGrid" Property="Background" Value="Red" />
</DataTrigger>
Run Code Online (Sandbox Code Playgroud)