问题
我需要制作使用图像作为背景的控件,这些控件可以是任何宽度,而不会扭曲图像。例如,如果我使用单个图像并对其进行拉伸,则图像的圆角会变形。
解决方案
Noxivs 给出的解决方案是使用自定义 UserControl,其中包含三个图像、两侧和一个被拉伸的中间。
将 SnapsToDevicePixels="True" 添加到 UserControl Grid 很重要,因为图像之间不会出现单个像素间隙。
主窗口.xaml
<Window x:Class="Testing.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ns="clr-namespace:Testing"
Title="MainWindow" Height="350" Width="525">
<Grid Name="MainGrid">
<ns:ScalableTextBox TextBoxText="Added in XAML" Width="120" Margin="0,0,0,100">
</ns:ScalableTextBox>
</Grid>
</Window>
主窗口.xaml.cs
ScalableTextBox scalableTextBox = new ScalableTextBox();
scalableTextBox.TextBoxText = "Added in C#";
scalableTextBox.Width = 100;
MainGrid.Children.Add(scalableTextBox);
ScalableTextBox.xaml.cs
public partial class ScalableTextBox : UserControl
{
public ScalableTextBox()
{
InitializeComponent();
}
public string TextBoxText
{
get { return this.TextBoxName.Text; }
set { this.TextBoxName.Text = value; }
}
}
ScalableTextBox.xaml
<UserControl x:Class="Testing.ScalableTextBox"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="36" d:DesignWidth="50" Height="36" MinWidth="29">
<Grid>
<Grid SnapsToDevicePixels="True">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="14" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="14" />
</Grid.ColumnDefinitions>
<Image Grid.Column="0" Source="pack://siteoforigin:,,,/Images/left.png" />
<Image Grid.Column="1" Stretch="Fill" Source="pack://siteoforigin:,,,/Images/center.png"/>
<Image Grid.Column="2" Source="pack://siteoforigin:,,,/Images/right.png" />
</Grid>
<TextBox Name="TextBoxName" VerticalAlignment="Center"
HorizontalAlignment="Center" Background="{x:Null}"
BorderBrush="{x:Null}" FontSize="12"/>
</Grid>
</UserControl>
再次感谢 Noxivs!