【问题标题】:WPF Button with Rectangle and OpacityMask带有 Rectangle 和 OpacityMask 的 WPF 按钮
【发布时间】:2016-10-22 00:46:12
【问题描述】:

我想制作一个类似于 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

【问题讨论】:

  • 好故事。但是你的问题是什么? (“我愿意”不是问题。)
  • 什么没有按预期工作?
  • 如何制作样式(如果需要)或一般如何制作?使用这个 xaml,整个按钮被填充,图像不可见。

标签: c# wpf opacitymask


【解决方案1】:

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

模板只是将内容添加到按钮。

简单的解决方案

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

在下面使用

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

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

希望这会有所帮助。

【讨论】:

  • 感谢您的努力,但这不是我想要的方式。图像颜色应该改变并且背景需要在任何情况下都是透明的。有没有办法改变矩形的填充,同时保持它的 OpacityMask 的 ImageSource (改变图像的颜色)?
  • 我建议的最好方法是使用 2 张图片来启用和禁用条件
猜你喜欢
  • 2015-04-22
  • 2010-12-28
  • 1970-01-01
  • 2022-06-13
  • 1970-01-01
  • 2011-02-11
  • 1970-01-01
  • 2011-02-14
  • 2013-07-01
相关资源
最近更新 更多