0

我想做一个像 Facebook 导航栏这样的 UI。我的想法是将按钮的背景设置为透明并在其上放置一个图标作为矩形的 OpacityMask 并更改它的填充。我对创建样式感到很困惑。

这是代码

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);
}

和 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>

我也喜欢任何想法以使其更容易。

facebook_sample_image

4

1 回答 1

0

样式中的“模板”将覆盖您从 c# 作为内容添加的图像

模板只是简单地向 Button 添加内容。

简单的解决方案

从 xaml 中的样式中删除“模板”。

下面使用

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

这将简单地更新按钮的背景并保持图像原样。

希望这可以帮助。

于 2016-10-23T05:00:41.617 回答