如何在 WPF 应用程序中设置和定位背景图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27535157/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 12:47:57  来源:igfitidea点击:

How to set and position a background Image in WPF application

wpfxamlviewwpf-controlsbackground-image

提问by Lynct

I need to add an image to my main window background. Here is what i have

我需要在我的主窗口背景中添加一个图像。这是我所拥有的

<Window.Background>
    <ImageBrush Stretch="None" AlignmentX="Center" AlignmentY="Center">
        <ImageBrush.Transform>
            <ScaleTransform ScaleX="0.5" ScaleY="0.5"/>
        </ImageBrush.Transform>

        <ImageBrush.ImageSource>
            <BitmapImage UriSource="/Assets/welcome.jpg"/>
        </ImageBrush.ImageSource>
    </ImageBrush>
</Window.Background>

for some reason, the unused spaces of my background becomes all black with this part of my code enter image description here

出于某种原因,我的背景中未使用的空间在我的这部分代码中变得全黑 在此处输入图片说明

So i have two questions

所以我有两个问题

  1. What causes the background goes all black and how can i fix it?
  2. I added the Alignments to my ImageBrush, why isnt the image centered?
  1. 是什么导致背景全黑,我该如何解决?
  2. 我将对齐添加到我的 ImageBrush,为什么图像不居中?

回答by Alexander Bell

In order to accurately position the Image(or any other control) in WPFapplication, it's recommended to create a layout grid in XAML, and place content in a proper cell, which might be centered, or placed in any area (like in this example, where image appears in the right-bottom corner: http://www.shopdigit.com/Pericles-TTS-14-for-Win-TTS-14-01.htm).

为了ImageWPF应用程序中准确定位(或任何其他控件),建议在 中创建布局网格XAML,并将内容放置在适当的单元格中,该单元格可能居中,或放置在任何区域(如本例中,其中图像出现在右下角:http: //www.shopdigit.com/Pericles-TTS-14-for-Win-TTS-14-01.htm)。

The following sample code snippet demonstrates this technique:

以下示例代码片段演示了此技术:

<Window x:Class="YourClass.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="YourTitle"
        ShowInTaskbar="True"
        WindowStartupLocation="CenterScreen">

    <!-- main layout grid-->
    <Grid>

    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="10*" />
        <ColumnDefinition Width="*" />
    </Grid.ColumnDefinitions>

    <Grid.RowDefinitions>
        <RowDefinition Height="*"/>
        <RowDefinition Height="10*"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>

        <TextBlock Grid.Row="1" Grid.Column="1">
                 <Image Margin="0,0,5,5" Source="[path to your image]" />
        </TextBlock>

    </Grid>
</Window>

Hope this will help. Best regards,

希望这会有所帮助。此致,