如何根据选定的值设置 WPF ComboBox 的 ToolTip?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15236294/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 07:54:13  来源:igfitidea点击:

How to set the ToolTip of WPF ComboBox based on selected value?

wpfcomboboxtriggerstooltipselectedvalue

提问by Relativity

I have a ComboBoxin my WPF application. Using below code I can set the ToolTipas selected value:

ComboBox我的 WPF 应用程序中有一个。使用下面的代码我可以设置ToolTip为选定的值:

ToolTip="{Binding Path=SelectedValue, RelativeSource={RelativeSource Self}}" 

But if I need to set a separate value for ToolTipbased on ComboBoxselection, the following code is not working:

但是如果我需要ToolTip根据ComboBox选择设置一个单独的值,下面的代码不起作用:

<controls:ComboBoxEx.Style>
    <Style TargetType="ComboBox" BasedOn="{StaticResource basicStyle}">
        <Style.Triggers>
            <DataTrigger Binding="{Binding Path=SelectedValue, RelativeSource={RelativeSource Self}}" Value="DAW">
                <Setter Property="ToolTip" Value="abc"/>
            </DataTrigger>

            <DataTrigger Binding="{Binding Path=SelectedValue, RelativeSource={RelativeSource Self}}" Value="generic">
                <Setter Property="ToolTip" Value="def"/>
            </DataTrigger>
        </Style.Triggers>
    </Style>
</controls:ComboBoxEx.Style>

采纳答案by sa_ddam213

I'm not sure if I understand correctly, but if you are using a Styleyou should not have to use a DataTriggeror RelativeSource={RelativeSource Self}}"to access SelectedValue, you should be able to access via a Triggerusing the Property

我不确定我的理解是否正确,但是如果您使用的是 a Style,则不必使用 aDataTriggerRelativeSource={RelativeSource Self}}"访问SelectedValue,您应该能够通过Trigger使用a进行访问Property

<Style TargetType="ComboBox">
    <Style.Triggers>
        <Trigger Property="SelectedValue"  Value="DAW">
            <Setter Property="ToolTip" Value="abc"/>
        </Trigger>
        <Trigger Property="SelectedValue" Value="generic">
            <Setter Property="ToolTip" Value="def"/>
        </Trigger>
    </Style.Triggers>
</Style>

回答by Syed Waqas

Bind the tooltip to the display property of the selected item in this case i have property name display, if you have declarative ComboBox items then that would be

将工具提示绑定到所选项目的显示属性,在这种情况下,我有属性名称显示,如果您有声明性 ComboBox 项目,那将是

ToolTip="{Binding Path=SelectedItem.Content,ElementName=cmbbox_years}"

Else for custom object below code will work

否则对于下面的代码自定义对象将起作用

<ComboBox 
  Name="cmbbox_years" 
  DisplayMemberPath="display" 
  SelectedValuePath="value"
  ItemsSource="{Binding Years}" 
  SelectedItem="{Binding YearSelectedItem}" 
  ToolTip="{Binding Path=SelectedItem.display,ElementName=cmbbox_years}"/>