WPF - Setting Custom tooltip using style triggers

♀尐吖头ヾ 提交于 2019-12-11 00:09:21

问题


I am trying to display tool tip to a stack panel based on property 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>

The code works fine. But it displays the tooltip under yellow background ( as normal tooltip). I need to customize it to change and include image. For that,

        <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>

It shows error when adding StackPanel to the . Please help me in solving.


回答1:


I don't know why that fails, but you can work around it by making the ToolTip a resource:

<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>

or

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

Also, the code you have will work as written in .NET 4, so the bug has been fixed.



来源:https://stackoverflow.com/questions/3583874/wpf-setting-custom-tooltip-using-style-triggers

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