创建包含图标/图像的文本框之类的内容

时间:2017-01-11 22:55:06

标签: c# wpf xaml textbox styling

我想做这样的事情:

enter image description here

所以它看起来像文本框,它可以写在中心所以它是文本框acctualy,但在左侧有放大镜的图标,在右侧有键盘的图标,但看起来像它的所有一个控制!

所以伙计们,有人可以帮助我创造这个吗?

如果我做下一件事是错的:

enter image description here

或者创建包含3列的网格更为正确?

  

第一列将包含放大镜图标

     

第二列将包含文本框

     

第三列将包含键盘图标

或者有第三种方式我不知道,而且我认为这种方法比这2种解决方案更好。

非常感谢! 这个社区是最好的!

1 个答案:

答案 0 :(得分:1)

  

或者用3列创建网格更正确?

是的,如果中间的TextBox没有固定的宽度会更好,因为StackPanel不会测量其子元素。

您可以向UserControl添加一个包含3列的Grid,并将元素的属性绑定到UserControl的依赖属性:

<强> UserControl1.xaml:

<UserControl x:Class="WpfApplication1.UserControl1"
             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" 
             xmlns:local="clr-namespace:WpfApplication1"
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300"
             x:Name="uc">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="Auto" />
        </Grid.ColumnDefinitions>
        <Image Grid.Column="0" Width="20" Height="20" />
        <TextBox Text="{Binding Text, ElementName=uc}" />
        <Image Grid.Column="1" Source="{Binding ImageSource, ElementName=uc}" Width="20" Height="20" />
    </Grid>
</UserControl>

<强> UserControl1.xaml.cs:

public partial class UserControl1 : UserControl
{
    public UserControl1()
    {
        InitializeComponent();
    }

    public static readonly DependencyProperty TextProperty =
         DependencyProperty.Register("Text", typeof(string), typeof(UserControl4));

    public string Text
    {
        get { return (string)GetValue(TextProperty); }
        set { SetValue(TextProperty, value); }
    }

    public static readonly DependencyProperty ImageSourceProperty =
        DependencyProperty.Register("ImageSource", typeof(Uri), typeof(UserControl4));

    public Uri ImageSource
    {
        get { return (Uri)GetValue(ImageSourceProperty); }
        set { SetValue(ImageSourceProperty, value); }
    }
}

<强>用法:

<local:UserControl1 Text="..." ImageSource="Images/screen.png" />