C# 在WPF中单击时更改圆形按钮的颜色
我有一个按钮的XAML代码。我需要这个按钮只是一个纯色的圆圈C# 在WPF中单击时更改圆形按钮的颜色,c#,wpf,xaml,events,button,C#,Wpf,Xaml,Events,Button,我有一个按钮的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 T
<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事件添加到椭圆并更改
(椭圆)发送方的属性
,但即使将椭圆添加为x:Name
属性,我也无法访问椭圆的颜色。我怎样才能做到这一点?谢谢!:) 您可以使用此代码实现您想要的功能。这至少是一个起点:
<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,然后从其他位置更改它。您可以这样做:
,然后在代码中调用((按钮)sender)。前景=笔刷.Black
如果你想重复使用它,你可以把它作为按钮的样式,像
一样使用它。同样,在样式上你可以像
@Strengat一样使用触发器-请把它作为一个答案而不是一个注释来写。评论很难找到和阅读。@ernodeweard这只是建议,不是完整的解决方案。首先,在回答这个问题之前,我需要从博世科那里了解更多的细节——然后,与其评论猜测,不如要求澄清。这就是评论的目的。很高兴您愿意提供帮助,并尽可能使您的贡献有价值,答案应该很容易找到和阅读。我对这段代码做了一些更改,实现了我想要的。非常感谢。