how can I set a background image in code?

限于喜欢 提交于 2019-11-27 19:39:52

问题


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>

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

TextBox myTextBox = new TextBox();

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?

Thank so much.


回答1:


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")));

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")));


来源:https://stackoverflow.com/questions/25804404/how-can-i-set-a-background-image-in-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!