从 C# 动态更改椭圆填充
Dynamically change ellipse fill from c#
我的 "ButtonStyles.xaml" 资源字典中有一个椭圆按钮模板。 这是代码的一部分:
<SolidColorBrush x:Key="brush" Color="Red"/>
<Style TargetType="Button" x:Key="MyButtonStyle">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<Grid>
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="CommonStates">
<VisualState x:Name="Normal">
<VisualState.Setters>
<Setter Target="ellipse.(Shape.Fill)" Value="{StaticResource ResourceKey=brush}">
</Setter>
<Setter Target="ellipse.(Shape.Stroke)" Value="{x:Null}"/>
</VisualState.Setters>
</VisualState>
[...]
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<Ellipse x:Name="ellipse"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
这是主页中的按钮:
<Button x:Name="toggle" Content="" HorizontalAlignment="Left" Height="132" Margin="40,146,0,0" VerticalAlignment="Top" Width="132" Style="{StaticResource MyButtonStyle}"/>
现在我想从c#代码中更改画笔资源。为此,我尝试如下:
Application.Current.Resources["brush"] = new SolidColorBrush(Windows.UI.Color.FromArgb(255, 125, 126, 126));
虽然画笔资源有效地改变了椭圆的颜色但没有。我认为问题是我不应该更改模板中的颜色,而应该更改实际的 MainPage 按钮中的颜色。 这是问题吗?我该怎么做?
我按照@felix-castor 的建议和 this 指南得到了结果。我在 C# 代码中放置了一个 DependencyProperty,在 XAML 代码中放置了一个 Binding。
它工作得很好,但是当 属性 更改时它不会刷新按钮,我必须在 VisualStates 之间切换以使其更新填充。我会 post 关于它的另一个问题。但是,如果您有任何建议,可以发表评论。