如果文本超出文本框的可用宽度,则显示工具提示

时间:2014-12-24 05:55:16

标签: c# wpf xaml

我试图在文本框中的文本超出文本框的可用大小时显示工具提示,我已经写了一个附加属性但是如果我在文本框上设置显式宽度,这可行,但是当重新调整窗口大小时它不会工作(当我重新调整窗口大小时,文本框的大小会减小)

我的XAML:

 <Window.Resources>
    <Style TargetType="TextBox">
        <Setter Property="local:TextBoxCropBehavior.TextBoxToolTip" Value="True"/>
        <Setter Property="BorderBrush" Value="Green"/>
    </Style>
</Window.Resources>
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="10"/>
        <RowDefinition Height="Auto"/>
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
    <TextBox Text=" first Textbox with long text dfdsfdsfdsfdslkjfwlekjorifdsfmldskfwepisdmfds;fdsfsfdsfdslkjfwlekjorifdsfmldskfwepisdmfds;fdsf"  x:Name="x" HorizontalAlignment="Right"/>
    <TextBox Text="Seceond text box" x:Name="y" Grid.Row="2" HorizontalAlignment="Right"/>
</Grid>

我的附属财产:

  public static class TextBoxCropBehavior
{
    public static bool GetTextBoxToolTip(DependencyObject obj)
    {
        return (bool)obj.GetValue(TextBoxCropToolTipProperty);
    }
    public static void SetTextBoxToolTip(DependencyObject obj, bool value)
    {
        obj.SetValue(TextBoxCropToolTipProperty, value);
    }

    public static readonly DependencyProperty TextBoxCropToolTipProperty = DependencyProperty.RegisterAttached("TextBoxToolTip", typeof(bool), typeof(TextBoxCropBehavior), new UIPropertyMetadata(false, OnTextCropChanges));
    private static void OnTextCropChanges(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var textbox = d as TextBox;
        textbox.SizeChanged += textbox_SizeChanged;
    }

    static void textbox_SizeChanged(object sender, SizeChangedEventArgs e)
    {
        var textbox = sender as TextBox;
        textbox.Measure(new Size(Double.MaxValue, Double.MaxValue));
        var width = textbox.DesiredSize.Width;

        if (textbox.ActualWidth < width)
        {
            ToolTipService.SetToolTip(textbox, textbox.Text);
        }
        else
        {
            ToolTipService.SetToolTip(textbox, null);
        }
    }
}

任何人都可以告诉我我在哪里做错了吗?

1 个答案:

答案 0 :(得分:0)

我不知道你是否必须使用附属财产。但试试这个。

我修改了TextBox的默认样式

<Window.Resources>
    <study:ToolTipConverter x:Key="ToolTipConverter"/>
    <Style TargetType="{x:Type TextBox}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type TextBox}">
                    <Themes:ListBoxChrome x:Name="Bd" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" RenderMouseOver="{TemplateBinding IsMouseOver}" RenderFocused="{TemplateBinding IsKeyboardFocusWithin}" SnapsToDevicePixels="True">
                        <Themes:ListBoxChrome.ToolTip>
                            <MultiBinding Converter="{StaticResource ToolTipConverter}">
                                <Binding ElementName="PART_ContentHost" Path="ScrollableWidth"/>
                                <Binding RelativeSource="{RelativeSource AncestorType={x:Type TextBox}}" Path="Text"/>
                            </MultiBinding>
                        </Themes:ListBoxChrome.ToolTip>
                        <ScrollViewer x:Name="PART_ContentHost" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
                    </Themes:ListBoxChrome>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsEnabled" Value="False">
                            <Setter Property="Background" TargetName="Bd" Value="{DynamicResource {x:Static SystemColors.ControlBrushKey}}"/>
                            <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}"/>
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</Window.Resources>
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="10"/>
        <RowDefinition Height="Auto"/>
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
    <TextBox Text=" first Textbox with long text dfdsfdsfdsfdslkjfwlekjorifdsfmldskfwepisdmfds;fdsfsfdsfdslkjfwlekjorifdsfmldskfwepisdmfds;fdsf" HorizontalAlignment="Right"/>
    <TextBox Text="Seceond text box" Grid.Row="2" HorizontalAlignment="Right"/>
</Grid>

转换器

public class ToolTipConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        if (values == null || values.Count() < 2 || values[0] == null) { return null; }
        if ((double)values[0] > 0) { return values[1]; }
        else { return null; }
    }


    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

编辑:行为版

<TextBox Text=" first Textbox with long text dfdsfdsfdsfdslkjfwlekjorifdsfmldskfwepisdmfds;fdsfsfdsfdslkjfwlekjorifdsfmldskfwepisdmfds;fdsf" HorizontalAlignment="Right" x:Name="PART_Textbox">
    <i:Interaction.Behaviors>
        <study:OptionalToolTipBehavior/>
    </i:Interaction.Behaviors>
</TextBox>

行为

public partial class MainWindow : Window
{

    public MainWindow()
    {
        InitializeComponent();
    }
}


public class OptionalToolTipBehavior : Behavior<TextBox>
{
    protected override void OnAttached()
    {
        this.AssociatedObject.Loaded += AssociatedObject_Loaded;
        base.OnAttached();
    }


    void AssociatedObject_Loaded(object sender, EventArgs e)
    {
        this.AssociatedObject.Loaded -= AssociatedObject_Loaded;

        ScrollViewer scrollViewer = this.FindScrollViewer(AssociatedObject);
        if (scrollViewer != null)
        {
            this.AssociatedObject.SetBinding(TextBox.ToolTipProperty,
                new Binding() { Source = scrollViewer, 
                    Path = new PropertyPath(ScrollViewer.ScrollableWidthProperty), 
                        Converter = ScrollableWithToTooltipConverter.Instance, 
                        ConverterParameter=this.AssociatedObject.Text});
        }
    }



    private ScrollViewer FindScrollViewer(DependencyObject element)
    {
        if (element is ScrollViewer) { return element as ScrollViewer; }

        int childCount = VisualTreeHelper.GetChildrenCount(element);
        for (int i = 0; i < childCount; i++)
        {
            return this.FindScrollViewer(VisualTreeHelper.GetChild(element, i));
        }
        return null;
    }



    private class ScrollableWithToTooltipConverter : IValueConverter
    {
        public static readonly ScrollableWithToTooltipConverter Instance = new ScrollableWithToTooltipConverter();

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if((double) value > 0)
            {
                return parameter.ToString();
            }
            return null;
        }


        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

}