如何在代码中设置背景图像? [英] how can I set a background image in code?

查看:30
本文介绍了如何在代码中设置背景图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

If I want to set a image as background on a textBox I can use this code in the axml:

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

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

However, I am creating a TextBlock in code, I amtrying this:

TextBox myTextBox = new TextBox();

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

But in this way I don't know how to access to the ImageBrush property.

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

Which is the way to add a background in code?

非常感谢.

推荐答案

如果MyImage.jpg是应用程序当前文件夹下的文件,可以写

Provided that MyImage.jpg is a file in the application's current folder, you could write

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

如果它是资源文件,则必须使用 资源文件包 URI:

If it's a Resource File, you would have to use a Resource File Pack URI:

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

这篇关于如何在代码中设置背景图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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