【问题标题】:how can I set a background image in code?如何在代码中设置背景图像?
【发布时间】:2014-11-06 09:41:08
【问题描述】:

如果我想将图像设置为文本框的背景,我可以在 axml 中使用此代码:

<Grid>
 <Grid.Background>
    <ImageBrush ImageSource="MyImage.jpg" />
 </Grid.Background>
 <TextBlock Text="Some Text" />
</Grid>

但是,我正在代码中创建一个 TextBlock,我正在尝试:

TextBox myTextBox = new TextBox();

但是这种方式我不知道如何访问 ImageBrush 属性。

在代码中添加背景的方法是什么?

非常感谢。

【问题讨论】:

标签: wpf textbox background-image


【解决方案1】:

假设MyImage.jpg是应用程序当前文件夹中的一个文件,你可以写

myTextBox.Background = new ImageBrush(new BitmapImage(new Uri("MyImage.jpg")));

如果是资源文件,则必须使用Resource File Pack URI:

myTextBox.Background =
    new ImageBrush(new BitmapImage(new Uri("pack://application:,,,/MyImage.jpg")));

【讨论】:

  • 我可以使用位图而不是 URI 吗?例如内存流或位图。
  • BitmapImage 也可以从 Stream 创建。请参阅here 或here。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-06-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-06
  • 2018-01-08
  • 1970-01-01
相关资源
最近更新 更多