【问题标题】:How to implement a textbox with a clear button in wpf?如何在 wpf 中实现带有清除按钮的文本框?
【发布时间】:2012-11-17 10:58:18
【问题描述】:

我有以下UserControl。这是一个TextBox 和一个Button

<Grid>
    <TextBox
        Grid.Column="0"
        Text="{Binding Text, 
               RelativeSource={RelativeSource AncestorType=UserControl}, 
               UpdateSourceTrigger=PropertyChanged}"
         x:Name="TextBox" />

     <Button
         Background="{Binding Background, ElementName=TextBox}"
         Grid.Column="1"
         Style="{StaticResource {x:Static ToolBar.ButtonStyleKey}}"
         HorizontalAlignment="Right"
         Visibility="{Binding IsClearButtonVisible,
                      RelativeSource={RelativeSource AncestorType=UserControl},
                      Converter={StaticResource BooleanToVisibilityConverter}}"
         Command="{Binding ClearTextCommand,
                   RelativeSource={RelativeSource AncestorType=UserControl}}"    
         HorizontalContentAlignment="Center"
         VerticalContentAlignment="Center" >

         <Button.Content>
             <Image
                 Source="{StaticResource Delete2}"
                 Stretch="None"
                 RenderOptions.BitmapScalingMode="NearestNeighbor"
                 VerticalAlignment="Center"
                 HorizontalAlignment="Center" />
        </Button.Content>
    </Button>
</Grid>

在 Windows 7 中看起来不错,但在 Windows XP 中出现以下问题:

关于如何解决此问题的任何想法?如果我使背景透明,那么按钮就没有问题,但是文本会在按钮下方并且看起来很奇怪。

【问题讨论】:

    标签: c# wpf user-controls textbox


    【解决方案1】:

    缩小Button 和/或添加一个小边距以“缩小”可见背景。

    编辑:环顾四周(想知道这还没有作为一些新功能添加)我发现this article with step-by-step instructions you could give a try

    【讨论】:

    • 如果我这样做了,那么在 W7 上,按钮比文本框小,当你悬停/点击它时,它看起来也很丑:(
    • 试试我链接的博文。
    【解决方案2】:

    试试这个。

    <TextBox x:Name="SearchFilter" VerticalAlignment="Center" Width="200"  
                                     Text="{Binding SearchItemString}" />
    <Button Margin="-20,10,5,0" Width="25" Height="25" Content="X" 
                            Style="{StaticResource TransparentStyle}" />
    

    这里是样式。

    <Style x:Key="TransparentStyle" TargetType="{x:Type Button}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="Button">
                    <Border Background="Transparent">
                        <ContentPresenter/>
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
    

    结果:

    【讨论】:

    • 相当快速和肮脏......谢谢。您甚至可以在 TextBox 中添加与按钮宽度相等的右边距,这样您的文本就不会出现在按钮下方。
    【解决方案3】:

    我认为你应该在这里使用ControlTemplates,例如你可以看到Search Text Box Controlhere你可以找到文本框模板

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-04-20
      • 1970-01-01
      • 1970-01-01
      • 2019-12-16
      • 1970-01-01
      • 2010-11-27
      • 1970-01-01
      相关资源
      最近更新 更多