【发布时间】:2011-03-07 06:17:57
【问题描述】:
我有一个问题:我想通过后面的代码设置网格的图像。
谁能告诉我怎么做?
【问题讨论】:
我有一个问题:我想通过后面的代码设置网格的图像。
谁能告诉我怎么做?
【问题讨论】:
通过在网格中添加以下代码,所有这些都可以在 xaml 中轻松实现
<Grid>
<Grid.Background>
<ImageBrush ImageSource="/MyProject;component/Images/bg.png"/>
</Grid.Background>
</Grid>
留给您做的是向解决方案添加一个名为“Images”的文件夹,并将现有文件添加到新的“Images”文件夹中,在本例中称为“bg.png”
【讨论】:
您是否忘记了Background 属性。画笔应该是 ImageBrush,其 ImageSource 可以设置为您的图像路径。
<Grid>
<Grid.Background>
<ImageBrush ImageSource="/path/to/image.png" Stretch="UniformToFill"/>
</Grid.Background>
<...>
</Grid>
【讨论】:
<Grid Background="{StaticResource yourBrush}" />
我的图像在一个单独的类库(“MyClassLibrary”)中,它们被放置在“图像”文件夹中。在示例中,我使用“myImage.jpg”作为背景图片。
ImageBrush myBrush = new ImageBrush();
Image image = new Image();
image.Source = new BitmapImage(
new Uri(
"pack://application:,,,/MyClassLibrary;component/Images/myImage.jpg"));
myBrush.ImageSource = image.Source;
Grid grid = new Grid();
grid.Background = myBrush;
【讨论】:
Image 毫无意义,因为您没有将它用于任何事情。您可以直接在ImageBrush 上设置ImageSource。
为了避免路径问题,你可以试试这个,只需将背景图片保存在 images 文件夹中并添加此代码
<Grid>
<Grid.Background>
<ImageBrush Stretch="Fill" ImageSource="..\Images\background.jpg"
AlignmentY="Top" AlignmentX="Center"/>
</Grid.Background>
</Grid>
【讨论】: