【问题标题】:Change color of circle button when clicked in WPF在 WPF 中单击时更改圆形按钮的颜色
【发布时间】:2019-01-03 02:41:04
【问题描述】:

我有这个用于按钮的 XAML 代码。我需要这个按钮只是一个纯色的圆圈。

<Button x:Name="btn_Color" Grid.Column="0" Grid.Row="2" HorizontalAlignment="Center" VerticalAlignment="Center" Height="25" Width="25" BorderBrush="Black">
    <Button.Template>
        <ControlTemplate TargetType="Button">
            <Grid>
                <Ellipse Fill="Black"/>
            </Grid>
        </ControlTemplate>
    </Button.Template>
</Button>

我希望这个按钮在我单击它时改变颜色,并且能够将此代码重用于其他按钮。稍后我会将颜色用于其他用途,因此我需要能够访问该数据。 我尝试将 PreviewMouseDown 事件添加到 Ellipse 并更改 (Ellipse)sender 上的属性,但即使我将其添加为 x:Name 属性,我也无法访问 Ellipse 的颜色。我怎样才能做到这一点?谢谢! :)

【问题讨论】:

  • 你可以做类似的事情:&lt;Ellipse Fill="{TemplateBinding Foreground}" /&gt; 然后,在你的代码中你可以调用((Button)sender).Foreground = Brushes.Black;
  • 如果你想重用它,你可以把它作为按钮的样式并像&lt;Button Foreground="Black" Style="{StaticResource YourButtonStyle}"/&gt;一样使用它。另外,在样式中你可以使用像&lt;Trigger Property="Pressed" Value="True"&gt;&lt;Setter Property="Foreground" Value="Green"/&gt;这样的触发器
  • @sTrenat - 请将其写为答案而不是评论。评论很难找到和阅读。
  • @ErnodeWeerd 这只是建议,而不是完整的解决方案。首先,在回答之前,我需要从 TheBosco 了解更多详细信息。
  • @sTrenat - 然后,不要评论猜测,而是要求澄清。这就是 cmets 的用途。很高兴您愿意提供帮助,并且为了使您的贡献尽可能有价值,答案应该易于查找和阅读。

标签: c# wpf xaml events button


【解决方案1】:

您可以使用此代码来实现您想要的。这至少是一个起点:

  <Button x:Name="btn_Color" Grid.Column="0" Grid.Row="2" HorizontalAlignment="Center" VerticalAlignment="Center" Height="25" Width="25">
        <Button.Style>
            <Style TargetType="Button">
                <Setter Property="BorderBrush" Value="Black"/>
                <Style.Triggers>
                    <Trigger Property="IsPressed" Value="True">
                        <Setter Property="BorderBrush" Value="Green"/>
                    </Trigger>
                </Style.Triggers>
            </Style>
        </Button.Style>
        <Button.Template>
            <ControlTemplate TargetType="Button">
                <Grid>
                    <Ellipse Fill="{Binding BorderBrush, RelativeSource={RelativeSource AncestorType=Button}}"/>
                </Grid>
            </ControlTemplate>
        </Button.Template>
    </Button>

这样做,您可以将 BorderBrush 绑定到不同的颜色或 DependencyProperty 并从其他地方更改。

【讨论】:

  • 我对这段代码做了一些修改,实现了我想要的。谢谢!
猜你喜欢
  • 1970-01-01
  • 2013-04-25
  • 1970-01-01
  • 2020-10-03
  • 2014-08-26
  • 1970-01-01
  • 2014-12-01
  • 2021-07-07
  • 2012-12-06
相关资源
最近更新 更多