WPF Button with Rectangle and OpacityMask

1.2k Views Asked by At

I would like to make an UI like Facebook navigation bar. My idea was to make the Background of the Button to Transparent and put an icon on it as an OpacityMask of a Rectangle and change the Fill of it. I've got so confused creating the Style.

Here's the Code

for (int i = 0; i < 6; i++)
{
    Button btn = new Button
    {
        Name = ("btnUi" + i).ToString(),
        Width = 42,
        Height = 42,
        Content = new Rectangle
        {
            Fill = Brushes.DarkBlue,
            OpacityMask = new ImageBrush
            {
                ImageSource = new BitmapImage(new Uri(Directory.GetCurrentDirectory() + @"\images\ui_0" + (i + 1).ToString() + ".png"))
            },
            VerticalAlignment = VerticalAlignment.Center,
            Width = 32,
            Height = 32
        },               
        Style = this.FindResource("uiStyle01") as Style
    };
    if (i == 0) btn.IsEnabled = false;
    btn.Click += btnUi_Click;
    uiPanel.Children.Add(btn);
}

And the App.xaml

<Application.Resources>
    <Style TargetType="Button" x:Key="uiStyle01">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type Button}">
                    <Rectangle x:Name="Rectangle" Fill="MidnightBlue">
                    </Rectangle>

                    <ControlTemplate.Triggers>
                        <Trigger Property="IsEnabled" Value="False">
                            <Setter TargetName="Rectangle" Property="Fill" Value="Gray"/>
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter> 
    </Style> 
</Application.Resources>

I appriciate any idea to make it easier too.

facebook_sample_image

1

There are 1 best solutions below

2
Satyajit Mohanty On

"Template" in Style will overwrite the Image you are adding as Content from c#

Template is simply add content to Button.

Simple solution

Remove "Template" from the style in xaml.

Use below

<Style TargetType="Button" x:Key="uiStyle01">
        <Style.Triggers>
            <Trigger Property="IsEnabled" Value="False">
                <Setter Property="Background" Value="Gray"/>
             </Trigger>
         </Style.Triggers>
</Style>

This will simply update the background of button and Keep the image as it is.

Hope this helps.