控件模板如何处理数据上下文?
使用以下模板
<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>
控制权
<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>
但是这并不会使背景变成红色。我已经验证了ToolbarViewModel属性
ToolSelected
的值实际上是Unlink,因为在控件旁边有一个<Label Content="{Binding ToolSelected}"/>
。所以我认为问题在于模板没有使用正确的DataContext
,但我不确定。这就是为什么我向您寻求帮助的原因。该控件位于自定义用户控件中,并且ToolbarViewModel被设置为其所有内容的上下文,如下所示。
<UserControl.DataContext>
<local:ToolboxView/>
</UserControl.DataContext>
ControlTemplate
覆盖了对象的所有属性。因此,一旦您为按钮设置了ControlTemplate
,给它设置Background
就没有意义了... - Omri Btian