我正在为我的WPF应用程序设计一个控件,我想在Button
内部TextBox
。 Button
将包含使用鼠标悬停更改的图像,但我已经知道如何执行该部分。我遇到的问题实际上是Button
中包含TextBox
,因此它只占用图像的空间并且是透明的。下面是我到目前为止尝试过的标记:
XAML:
<Grid>
<TextBox x:Name="SearchBoxView" HorizontalAlignment="Right" Width="200" Margin="5, 5, 10, 5" FontSize="16" KeyUp="SearchBoxKeyDown" Text="{Binding SearchText, Mode=TwoWay}" Grid.Column="0"/>
<Button Background="Transparent" HorizontalAlignment="Right" HorizontalContentAlignment="Center" VerticalContentAlignment="Center">
<Button.Content>
<Image Source="Image.png" Stretch="None" RenderOptions.BitmapScalingMode="NearestNeighbor" VerticalAlignment="Center" HorizontalAlignment="Center"/>
</Button.Content>
</Button>
</Grid>
我接着提出了这个问题:How to implement a textbox with a clear button in wpf?,它也与本文有关:WPF Search Text Box。问题中建议的XAML不起作用,我认为这是因为他们使用的Style
,我无法访问。这篇文章提供了太多的信息,主要讨论了在鼠标悬停时交换搜索和删除图标所需的触发器和依赖属性。所以,我正在寻求帮助,找到一个如何实现这一目标的简单解决方案。谢谢!
XAML:
<Grid Margin="5, 5, 10, 5">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<TextBox x:Name="SearchBoxView" HorizontalAlignment="Right" Width="200" FontSize="16" KeyUp="SearchBoxKeyDown" Text="{Binding SearchText, Mode=TwoWay}" Grid.Column="0"/>
<Button Background="{Binding Backgound, ElementName=SearchBoxView}" HorizontalAlignment="Right" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" Click="SearchBoxViewButtonClick" Grid.Column="1">
<Button.Template>
<ControlTemplate>
<Border HorizontalAlignment="Center" VerticalAlignment="Center">
<Image Source="Image.png" Width="12" Height="12"/>
</Border>
</ControlTemplate>
</Button.Template>
</Button>
</Grid>
图像:
答案 0 :(得分:5)
指定Button
模板,而不是内容
<Button>
<Button.Template>
<ControlTemplate>
<Border HorizontalAlignment="Center" VerticalAlignment="Center" >
<Image Source="pack://application:,,,/Organizr;component/DataLayer/Images/ActiveDeleteIcon.png"
Width="16"
Height="16"/>
</Border>
</ControlTemplate>
</Button.Template>
</Button>
修改强>
顺便说一句,在您的情况下,图片将覆盖TextBox
并输入文字。我建议将这些控件放在网格的不同列中,如下面的
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<TextBox x:Name="SearchBoxView"
HorizontalAlignment="Right"
Width="200" Margin="5, 5, 10, 5"
FontSize="16"
KeyUp="SearchBoxKeyDown"
Text="{Binding SearchText, Mode=TwoWay}"
Grid.Column="0"/>
<Button
Grid.Column="1"
Background="Transparent"
HorizontalAlignment="Right"
HorizontalContentAlignment="Center" VerticalContentAlignment="Center">
<ControlTemplate>
<Border HorizontalAlignment="Center" VerticalAlignment="Center" >
<Image Source="pack://application:,,,/Organizr;component/DataLayer/Images/ActiveDeleteIcon.png"
Width="16"
Height="16"/>
</Border>
</ControlTemplate>
</Button.Template>
</Button>