wpf 如何在wpf中实现带有清除按钮的文本框?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13624606/
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
How to implement a textbox with a clear button in wpf?
提问by Ignacio Soler Garcia
I have the following UserControl. It's a TextBoxwith a Button:
我有以下内容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>
In Windows 7 it looks great but in Windows XP I have the following issue:
在 Windows 7 中它看起来不错,但在 Windows XP 中我有以下问题:


Any ideas on how to fix the issue? If I make the background transparent then there is no problem with the button but the text gets below the button and looks weird.
关于如何解决问题的任何想法?如果我将背景设置为透明,那么按钮就没有问题,但是文本位于按钮下方并且看起来很奇怪。
采纳答案by Mario
Make the Buttonsmaller and/or add a small margin to "downsize" the visible background.
使Button较小的和/或添加少量保证金“缩小”可见背景。
Edit: While looking around a bit (wondering that this hasn't been added as some new Feature) I've found this article with step-by-step instructions you could give a try.
编辑:环顾四周(想知道这还没有作为一些新功能添加)时,我发现这篇文章包含您可以尝试的分步说明。
回答by Rustem
I think you should use ControlTemplates here, as example you can see Search Text Box Controland hereyou can find textbox template
回答by cnuis2cool
Try this.
尝试这个。
<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}" />
Here is the Style.
这里是样式。
<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>

