C# 如何在wpf中实现带有清除按钮的文本框?

C# 如何在wpf中实现带有清除按钮的文本框?,c#,wpf,user-controls,textbox,C#,Wpf,User Controls,Textbox,我有以下UserControl。这是一个带有按钮的文本框: <Grid> <TextBox Grid.Column="0" Text="{Binding Text, RelativeSource={RelativeSource AncestorType=UserControl}, UpdateSourceTrigger=PropertyChanged}" x

我有以下
UserControl
。这是一个带有
按钮的
文本框

<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中,我有以下问题:


关于如何解决这个问题有什么想法吗?如果我将背景设置为透明,则按钮没有问题,但文本位于按钮下方,看起来很奇怪。

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


编辑:我四处看了看(不知道这还没有被添加为新功能),发现了。

我认为您应该在这里使用
ControlTemplate
s,如您所见 你可以找到文本框模板,试试这个

<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>

结果:

如果我这样做,那么在W7上,按钮比文本框小,当你胡佛/点击它时,它看起来也很难看:(试试我链接的博客帖子。非常快而且很脏……谢谢。你甚至可以在文本框中添加与按钮宽度相等的填充,这样你的文本就不会在按钮下面。