2016-03-06 30 views
0

所以,我在资源字典中有一个按钮模板。它的正常VisualState中的颜色属性绑定到MainPage C#代码中定义的DependencyProperty。请注意,MainControl是MainPage名称。 这里的按钮模板:更改样式颜色后的刷新按钮

<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="{Binding ElementName=MainControl, Path=ButtonColor}"> 
            </Setter> 
            <Setter Target="ellipse.(Shape.Stroke)" Value="{x:Null}"/> 
           </VisualState.Setters> 
          </VisualState> 
          [Other Visual States...] 
         </VisualStateGroup> 
        </VisualStateManager.VisualStateGroups> 
        <Ellipse x:Name="ellipse"/> 
       </Grid> 
      </ControlTemplate> 
     </Setter.Value> 
    </Setter> 
</Style> 

这里的的MainPage XAML:

<Page 
x:Class="Volumio.MainPage" 
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
xmlns:local="using:Volumio" 
Name="MainControl"> 
<Grid Background="#FF525C66"> 
    <Button x:Name="toggle" Content="" HorizontalAlignment="Left" Height="132" Margin="40,146,0,0" VerticalAlignment="Top" Width="132" Style="{StaticResource MyButtonStyle}"> 
</Grid> 

而且这里是我定义的属性:

public static DependencyProperty ColorProperty = DependencyProperty.Register("ButtonColor", typeof(SolidColorBrush), 
     typeof(Page), PropertyMetadata.Create(NormalColor)); 

    public SolidColorBrush ButtonColor 
    { 
     get { return (SolidColorBrush)GetValue(ColorProperty); } 
     set { SetValue(ColorProperty, value); } 
    } 

的问题是:当我将ButtonColour属性设置为不同的颜色,Button不自动更改颜色,而不是必须更改VisualState,然后返回到正常状态以使其刷新并更改颜色。我改变了异步空洞中的属性。这很重要吗?

问题在哪里?我需要从代码中手动刷新它吗?

这可能很明显,但我是XAML编程的新手。提前致谢。

回答

0

Setter s在VisualState下仅在使用VisualState作为当前状态时应用一次。当应用Setter时,它将从其Value属性获取值并将其设置为其Target属性中指定的目标元素和属性。

所以不会设置你的BindingellipseFill财产,除非按钮的VisualState再次成为Normal你按钮将不会改变它的颜色。

如果要自动的按钮改变颜色,你可以删除<Setter Target="ellipse.(Shape.Fill)" Value="{Binding ElementName=MainControl, Path=ButtonColor}"></Setter>VisualState.Setters和使用BindingEllipse,如:

<Ellipse x:Name="ellipse" Fill="{Binding ElementName=MainControl, Path=ButtonColor}" /> 

,或重复这个Style,我们可以绑定Fill属性Button的使用

<Ellipse x:Name="ellipse" Fill="{TemplateBinding Background}" /> 

和XAML的MainPage:Background财产这样

<Button x:Name="toggle" 
    Width="132" 
    Height="132" 
    Margin="40,146,0,0" 
    HorizontalAlignment="Left" 
    VerticalAlignment="Top" 
    Background="{Binding ElementName=MainControl, 
         Path=ButtonColor}" 
    Style="{StaticResource MyButtonStyle}" /> 
+0

是Jay Zuo,它工作完美。我删除了VisualStates,因为我要通过C#控制它们。非常感谢 :-) – MasterArch