开发者

WPF overlay help

开发者 https://www.devze.com 2023-01-30 16:41 出处:网络
i am trying to create an overlay like this when mouse move over image control. how to I do it using WPF ?

i am trying to create an overlay like this when mouse move over image control. how to I do it using WPF ?

开发者_如何学Python

please advice

WPF overlay help


You create both the image and the overlay, and bind the visibility property of the overlay to the image's and the overlay's IsMouseOver property.

You can also do it with triggers instead of binding. It works too.

Update: Here is sample code. The XAML can look like this:

<Grid>
    <Grid.Resources>
        <local:OverlayVisibilityConverter x:Key="OverlayVisibilityConverter" />
    </Grid.Resources>
    <Image x:Name="myImage" Source="MyImage.JPG" />
    <Image x:Name="myOverlay" 
           Source="MyOverlay.jpg"
           VerticalAlignment="Center"
           Opacity="0.2">
        <Image.Visibility>
            <MultiBinding Converter="{StaticResource OverlayVisibilityConverter}">
                <Binding ElementName="myOverlay" Path="IsMouseOver" />
                <Binding ElementName="myImage" Path="IsMouseOver" />
            </MultiBinding>
        </Image.Visibility>
    </Image>
</Grid>

Of course the overlay must not be an image and can be anything. I just used an image in the sample. The opacity can be anything between 0 and 1.

The code for the converter can look like this:

   class OverlayVisibilityConverter : IMultiValueConverter
    {
        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
            var isMouseOverOverlay = (bool)values[0];
            var isMouseOverImage = (bool)values[1];

            if (isMouseOverImage || isMouseOverOverlay)
                return Visibility.Visible;
            else
                return Visibility.Hidden;
        }

        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }


I didn't like the complexity of the other answer as I felt it was too much for something so simple, so I tried it using MouseEnter and MouseLeave events and it seems to work quite well.

XAML:

<Grid MouseEnter="Grid_MouseEnter" MouseLeave="Grid_MouseLeave">
    <Image x:Name="MainImage" Source="..." />
    <Image x:Name="OverlayImage" Source="..." />
</Grid>

With accompanying code:

private void Grid_MouseEnter(object sender, MouseEventArgs e)
{
    OverlayImage.Visibility = System.Windows.Visibility.Visible;
}

private void Grid_MouseLeave(object sender, MouseEventArgs e)
{
    OverlayImage.Visibility = System.Windows.Visibility.Collapsed;
}

You don't need to use an image for the overlay, it can be anything. In my real case I actually had a StackPanel overlay which contained buttons for edit and delete (so the user could change/remove the image)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号