Opacity mask an image in wpf weird bahvior

1.7k Views Asked by At

I try to make an opacity mask for an image in wpf via this xaml:

<Border x:Name="border1" Margin="20" BorderThickness="2" BorderBrush="Red" CornerRadius="50" >
    <Grid>
        <Border Background="Wheat" x:Name="border2" CornerRadius="50"/>
        <Image Margin="0" Source="Images/SpiderMan.png" Stretch="Fill">
            <Image.OpacityMask>
                <VisualBrush Visual="{Binding ElementName=border2}"/>
            </Image.OpacityMask>
        </Image>
    </Grid>
</Border>

this xaml works properly and is fine, but when i change Elementname to border1 that does not work? why this happens?

Edited(another question):

in above xaml, image do not show until i set Background property of border2 but wht this happens? why without background property image do not show?

1

There are 1 best solutions below

5
On BEST ANSWER

Border1 can't be assigned to VisualBrush since it is a parent control. If such binding will be allowed.. you will faced with huge recursion and stackoverflow exception. Next XAML shold work

<Grid>
     <Border x:Name="border1" Margin="20" BorderThickness="2" BorderBrush="Red" CornerRadius="50" />
    <Grid>
        <Border Background="Wheat" x:Name="border2" CornerRadius="50"/>
        <Image Margin="0" Source="Images/SpiderMan.png" Stretch="Fill">
            <Image.OpacityMask>
                <VisualBrush Visual="{Binding ElementName=border1}"/>
            </Image.OpacityMask>
        </Image>
    </Grid>
</Grid>