wpf在鼠标悬停时更改TextBox宽度

时间:2014-11-19 13:29:28

标签: wpf visibility

我的ListBoxItem里面有Textbox。鼠标悬停显示文本框后面的可拖动块。文本框自动调整到其内容,这没关系,但是当Drag apperas,ListboxItem变得更宽并移动其他项目时,它就不行了。所以当Drag折叠时我需要TextBox比它的内容宽一点:

             onMouseOver
+---------+  +----+----+
|text     |  |drag|text|
+---------+  +----+----+

我猜:显示拖动一点,然后折叠,并将Textbox.width绑定到某些Border.ActualWidth:

 <Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="auto"/>
        <ColumnDefinition />
    </Grid.ColumnDefinitions>

    <DockPanel x:Name="drag" Width="15" >
        <DockPanel.Style>
            <Style TargetType="DockPanel">
            <!--<Setter Property="Visibility" Value="Collapsed" />-->
                <!--<Style.Triggers>
                    <DataTrigger Binding="{Binding IsMouseOver, RelativeSource={RelativeSource AncestorType=ListBoxItem}}" Value="True">
                        <Setter Property="Visibility" Value="Visible" />
                    </DataTrigger>
                </Style.Triggers>-->
            </Style>
        </DockPanel.Style>
    </DockPanel>

    <Border x:Name="bd" Grid.ColumnSpan="2" />

    <TextBox x:Name="query" Grid.Column="1">
        <TextBox.Style>
            <Style TargetType="TextBox">                   
                <!--<Style.Triggers>
                    <DataTrigger Binding="{Binding IsMouseOver, RelativeSource={RelativeSource AncestorType=ListBoxItem}}" Value="False">
                        <Setter Property="Width" Value="{Binding ActualWidth, ElementName=bd}" />
                    </DataTrigger>
                </Style.Triggers>-->
            </Style>
        </TextBox.Style>
    </TextBox>
</Grid>

我在代码中创建所有样式:

var dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
dispatcherTimer.Tick += (s1, e1) =>
{
    var mouseOverB = new Binding("IsMouseOver")
    {
        RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor, typeof(ListBoxItem), 1)
    };

    var actualB = new Binding("ActualWidth")
    {
        ElementName = "bd"
    };

    var setterVisible = new Setter(DockPanel.VisibilityProperty, Visibility.Visible);
    var setterCollapsed = new Setter(DockPanel.VisibilityProperty, Visibility.Collapsed);
    var setterWidth = new Setter(TextBox.WidthProperty, actualB);

    var panelTr = new DataTrigger()
    {
        Binding = mouseOverB,
        Value = true,
        Setters = { setterVisible }
    };

    var panelStyle = new Style(typeof(DockPanel))
    {
        Triggers = { panelTr },
        Setters = { setterCollapsed }
    };


    var txtTr = new DataTrigger()
    {
        Binding = mouseOverB,
        Value = false,
        Setters = { setterWidth }
    };

    var txtStyle = new Style(typeof(TextBox))
    {
        Triggers = { txtTr }
    };

    drag.Style = panelStyle;
    query.Style = txtStyle;
};
dispatcherTimer.Interval = new TimeSpan(0, 0, 0, 0, 50);
dispatcherTimer.Start();

这有效,但我有其他风格,并希望在XAML中进行。有什么建议吗?

0 个答案:

没有答案