首页 > 解决方案 > UserControl 中的图像使 UserControl 不可见,但使 Window 背景可见

问题描述

我举了这个制作圆形玻璃按钮的例子,并用它制作了一个影响最小的用户控件。第三个按钮是我的用户控制,所有其他按钮 - 来自示例:(对不起,声誉不足以以舒适的方式放置图像)

https://i.imgur.com/aBE8AjQ.png

但就在我将图像添加到控制之后,我看到了

https://i.imgur.com/FYPItVf.png

图像的添加方式与第二个按钮相同

            <Button Style="{StaticResource GlassButton}" Width="50" Height="50" Background="#FF1D5BBA"  Margin="10">
                <Image Width="40" Height="35" Source="images\vista_flag.png"/>
            </Button>

            <GlassButtonControl:GlassButton Width="70" Height="70" Margin="0">
                <Image Width="40" Height="35" Source="images\vista_flag.png"/>
            </GlassButtonControl:GlassButton>

完整的解决方案

我究竟做错了什么?

编辑1 -> 编辑3

编辑2:

正如 Peter Duniho 所说,重现案例的最小代码

UserControl 项目的 XAML。带彩色背景的按钮:

<UserControl x:Class="GreenButtonControl.GreenButton"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:local="clr-namespace:GreenButtonControl"
             mc:Ignorable="d" 
             d:DesignHeight="400" d:DesignWidth="400">
    <Grid>
        <Button Width="50" Height="50" Background="Green"  Margin="10"/>
    </Grid>
</UserControl>

UserControl 项目的 C#:

using System.Windows.Controls;

namespace GreenButtonControl
{
    public partial class GreenButton : UserControl
    {
        public GreenButton()
        {
            InitializeComponent();
        }
    }
}

Window XAML(图像本身应更改为任何现有的具有透明度的):

<GreenButtonControl:GreenButton Width="50" Height="50">
    <Image Width="40" Height="40" Source="images\vista_flag.png"/>
</GreenButtonControl:GreenButton>

问题是 UserControl 消失并且 Window 背景显示在透明图像下。

编辑3:

我现在找到的避免这种行为的解决方案:

  1. 将 Image 放在 UserControl 代码中并制作参数以从 Window 代码中设置它。
  2. 将图像不在控件内,而是在控件上:
            <Grid Width="70" Height="70">
                <GlassButtonControl:GlassButton/>
                <Image Width="40" Height="40" Source="images\vista_flag.png"/>
            </Grid>

但这带来了新的问题来捕捉触发器“MouseOver”和其他......

  1. 将 UserControl 放在容器中并使 Image 对鼠标事件透明
            <Grid Width="50" Height="50">
                <GreenButtonControl:GreenButton Width="Auto" Height="Auto"/>
                <Image Width="40" Height="40" IsHitTestVisible="False" Source="images\vista_flag.png"/>
            </Grid>

这是目前所需行为的完美决定

但问题仍然存在。为什么任何内部元素都使 UserControl 不可见?

标签: c#wpfuser-controls

解决方案


推荐阅读