WPF - 使用样式触发器设置自定义工具提示

man*_*ani 3 wpf triggers styles tooltip

我正在尝试根据属性 HasValidationError 向堆栈面板显示工具提示。

        <Style TargetType="StackPanel" x:Key="stackstyle">
            <Style.Triggers>
                <DataTrigger Binding="{Binding HasValidationError}" Value="True">
                    <Setter Property="ToolTip">
                        <Setter.Value>
                            <Binding Path="DisplayError"/>
                        </Setter.Value>
                    </Setter>
                </DataTrigger>
            </Style.Triggers>
        </Style>
Run Code Online (Sandbox Code Playgroud)

该代码工作正常。但它在黄色背景下显示工具提示(作为普通工具提示)。我需要自定义它以更改和包含图像。为了那个原因,

        <Style TargetType="StackPanel" x:Key="stackstyle">
            <Style.Triggers>
                <DataTrigger Binding="{Binding HasValidationError}" Value="True">
                    <Setter Property="ToolTip">
                        <Setter.Value>
                            <StackPanel>
                                 <!-- Have to add image and other decorations here -->
                                 <TextBlock Text = "{Binding DisplayError}"/>
                            </StackPanel>
                        </Setter.Value>
                    </Setter>
                </DataTrigger>
            </Style.Triggers>
        </Style>
Run Code Online (Sandbox Code Playgroud)

将 StackPanel 添加到 . 请帮我解决。

Qua*_*ter 5

我不知道为什么会失败,但您可以通过将 ToolTip 设为资源来解决它:

<StackPanel x:Key="ToolTipContents">
    <!-- Have to add image and other decorations here -->
    <TextBlock Text = "{Binding DisplayError}"/>
</StackPanel>
<Style TargetType="StackPanel" x:Key="stackstyle">
    <Style.Triggers>
        <DataTrigger Binding="{Binding HasValidationError}" Value="True">
            <Setter Property="ToolTip" Value="{StaticResource ToolTipContents}"/>
        </DataTrigger>
    </Style.Triggers>
</Style>
Run Code Online (Sandbox Code Playgroud)

或者

<ToolTip x:Key="ToolTipContents">
    <StackPanel>
        <!-- Have to add image and other decorations here -->
        <TextBlock Text = "{Binding DisplayError}"/>
    </StackPanel>
</ToolTip>
<!-- etc -->
Run Code Online (Sandbox Code Playgroud)

此外,您拥有的代码将按照 .NET 4 编写的方式工作,因此该错误已得到修复。