将图标放在XAML(WPF)的文本框中 [英] Putting icon in a textbox in XAML (WPF)

查看:837
本文介绍了将图标放在XAML(WPF)的文本框中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在文本框的角落放一个小图标(png文件)。我的意思草图是 http://dosketch.com/view.php?k=mIPeHLSBLx0e2YpoVpYO

I want to put a small icon (a png file) in to the corner of a textbox. A sketch of what I mean is at http://dosketch.com/view.php?k=mIPeHLSBLx0e2YpoVpYO

到目前为止,我已经(在我的主要xaml文件中)

So far I've got (in my main xaml file)

<TextBox Style="{StaticResource IconTextBox"} ...

和在我的资源区域:

<Style x:Key="IconTextBox" TargetType="TextBox">
 <Setter Property="Template">
  <Setter.Value>
   <ControlTemplate TargetType="TextBox">
     <Image Source="icon.png" />
   </ControlTemplate>
  </Setter.Value>
 </Setter>
</Style>

显然这不起作用(我开始丢失文本框!)。理想情况下,当用户在文本框中输入内容时,文本不会与图像重叠 - 但暂时我会很高兴在文本框中获取图像。

Obviously this isn't working (I'm losing the textbox for a start!). Ideally when the user is typing into the textbox, the text doesn't overlap the image - but for the time being I'll just be happy getting the image in the textbox.

谢谢

推荐答案

我会创建一个新的简单UserControl,而不是覆盖模板:

Instead of overwriting the template, I would create a new simple UserControl:

//pseudocode, does not compile!
<UserControl x:Class="MyUserControl" x:Name="root">
    <Grid>
        <!-- put some effort in aligning the items so it looks nice -->
        <TextBox Text="{Binding ElementName=root, Path=Text}" />
        <Image Source="{Binding ElementName=root, Path=IconSource}" />
    </Grid>
</UserControl>

public class MyUserControl : UserControl{
    dependencyproperty string Text;
    dependencyproperty string IconSource;
}

所以你可以按如下方式使用它:

so you can use it as follows:

<my:MyUserControl Text="{Binding MyText}" IconSource="{Binding MyIcon}"/>

这篇关于将图标放在XAML(WPF)的文本框中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆