【问题标题】:Set background image on grid in WPF using C#使用 C# 在 WPF 中的网格上设置背景图像
【发布时间】:2011-03-07 06:17:57
【问题描述】:

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

谁能告诉我怎么做?

【问题讨论】:

    标签: c# wpf


    【解决方案1】:

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

    <Grid>
        <Grid.Background>  
            <ImageBrush ImageSource="/MyProject;component/Images/bg.png"/>     
        </Grid.Background>
    </Grid>
    

    留给您做的是向解决方案添加一个名为“Images”的文件夹,并将现有文件添加到新的“Images”文件夹中,在本例中称为“bg.png”

    【讨论】:

    • 这是最好的答案@Shashank
    • 问题是在后面的代码中设置图像。
    【解决方案2】:

    您是否忘记了Background 属性。画笔应该是 ImageBrush,其 ImageSource 可以设置为您的图像路径。

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

    【讨论】:

    • 你能告诉我这个的确切语法吗
    • @SHASHANK:语法应该是这样的:&lt;Grid Background="{StaticResource yourBrush}" /&gt;
    【解决方案3】:

    我的图像在一个单独的类库(“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
    【解决方案4】:

    为了避免路径问题,你可以试试这个,只需将背景图片保存在 images 文件夹中并添加此代码

    <Grid>
      <Grid.Background>
        <ImageBrush Stretch="Fill" ImageSource="..\Images\background.jpg"
                    AlignmentY="Top" AlignmentX="Center"/>
      </Grid.Background>
    </Grid>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-12
      • 1970-01-01
      • 2015-08-20
      • 2020-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-14
      相关资源
      最近更新 更多