【问题标题】:Tooltip for each item in combobox组合框中每个项目的工具提示
【发布时间】:2019-06-08 17:20:15
【问题描述】:

我正在尝试为我的组合框中的每个用户名(CreatedBy)添加一个工具提示,以防用户名对于组合框的宽度来说太长。

我知道这个问题已经被问过一百万次了,我尝试过使用 Style.Triggers 方法,我也尝试过 ToolTip="{Binding Path=SelectedCreatedBy.ToolTip, RelativeSource={RelativeSource Self}}

<ComboBox ItemsSource="{Binding CreatedBys.DefaultView}" SelectedValue="{Binding SelectedCreatedBy,UpdateSourceTrigger=PropertyChanged}" SelectedValuePath="CreatedBy" DisplayMemberPath="CreatedBy" ToolTip="{Binding SelectedCreatedBy}" 
    Grid.Row="3" Grid.Column="12" Height="22" Width="85" FontSize="11" IsEditable="{Binding IsCreatedByEditable}" VerticalAlignment="Top" HorizontalAlignment="Left" >

编辑:我找到了解决方案,我将在此处发布代码

<ComboBox ItemsSource="{Binding CreatedBys.DefaultView}" SelectedValue="{Binding SelectedCreatedBy,UpdateSourceTrigger=PropertyChanged}" SelectedValuePath="CreatedBy" DisplayMemberPath="CreatedBy" ToolTip="{Binding SelectedCreatedBy}" 
          Grid.Row="3" Grid.Column="12" Height="22" Width="85" FontSize="11" IsEditable="{Binding IsCreatedByEditable}" VerticalAlignment="Top" HorizontalAlignment="Left" >
<ComboBox.ItemContainerStyle>
    <Style>
        <Setter Property="Control.ToolTip" Value="{Binding CreatedBy}" />
    </Style>
      </ComboBox.ItemContainerStyle>
 </ComboBox>

【问题讨论】:

    标签: wpf vb.net xaml


    【解决方案1】:

    如果我理解正确,您希望为每个组合框选项(而不仅仅是选定的选项)显示一个工具提示。如果是这种情况,请在您的 ComboBox 中添加以下代码:

    <ComboBox.ItemTemplate>
        <DataTemplate>
            <TextBlock
                Text="{Binding CreatedBy}"
                ToolTip="{Binding ToolTip}"
                />
        </DataTemplate>
    </ComboBox.ItemTemplate>
    
    <ComboBox.ItemContainerStyle>
        <Style TargetType="ComboBoxItem">
            <Setter Property="HorizontalContentAlignment" Value="Stretch" />
        </Style>
    </ComboBox.ItemContainerStyle>
    

    ItemTemplate 为每个项目定义了一个 TextBlockToolTip 绑定到您的视图模型的 ToolTip 属性。 ItemContainerStyle 拉伸 ComboBoxItem 以便即使鼠标不是直接在文本上而是在项目上也会出现工具提示。

    【讨论】:

    • 我在尝试使用您的建议时收到此错误消息。 System.Windows.Markup.XamlParseException HResult=0x80131501 Message='设置属性'System.Windows.Controls.ItemsControl.ItemTemplate'引发异常。'行号“169”和行位置“71”。内部异常 1:InvalidOperationException:无法同时设置 DisplayMemberPath 和 ItemTemplate。
    • @Brooke 尝试从您的ComboBox 中删除DisplayMemberPath 属性。您将不再需要它,因为 TextBlock 直接绑定到 CreatedBy 属性。
    • 这次尝试构建没有错误,但没有任何工具提示起作用,默认情况下组合框将显示 (ALL) 然后当您单击其他选项时,现在它显示 System.Datarowview没有点击时默认。
    • 听起来绑定不正确。您介意粘贴您的视图模型代码(尽可能简化)吗?您可以使用添加的代码附加您的问题。
    • 我找到了解决方案并继续将其添加到我原来的问题中。感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多