使用C#在WPF中设置网格上的背景图像

Sha*_*ank 42 c# wpf

我有一个问题:我想通过后面的代码设置我的网格图像.

谁能告诉我怎么做?

Jan*_*Jan 67

通过在网格中添加以下代码,可以在xaml中轻松实现所有这些功能

<Grid>
    <Grid.Background>  
        <ImageBrush ImageSource="/MyProject;component/Images/bg.png"/>     
    </Grid.Background>
</Grid>
Run Code Online (Sandbox Code Playgroud)

留给你的是,在解决方案中添加一个名为'Images'的文件夹,并将现有文件添加到新的'Images'文件夹中,在这种情况下称为'bg.png'

  • 问题是在代码后面设置图像。 (2认同)

Ams*_*nna 50

你忘记了背景属性吗?画笔应该是ImageBrush,其ImageSource可以设置为您的图像路径.

<Grid>
    <Grid.Background>
        <ImageBrush ImageSource="/path/to/image.png" Stretch="UniformToFill"/>
    </Grid.Background>

    <...>
</Grid>
Run Code Online (Sandbox Code Playgroud)


AH.*_*AH. 24

我将我的图像放在一个单独的类库("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;          
Run Code Online (Sandbox Code Playgroud)

  • 创建那个`Image` 是没有意义的,因为你没有将它用于任何事情。你可以直接在`ImageBrush`上设置`ImageSource`。 (2认同)