2016-06-09 71 views
1

我正在为提交按钮编写自定义渲染器,以便使用我的Xamarin.Forms应用程序提供统一样式。我无法在Windows(UWP)端设置禁用按钮的前景(文本)颜色。在代码中设置禁用按钮的前景色(UWP)

改变为激活键的颜色很简单,只要

Control.Foreground = new SolidColorBrush(Windows.UI.Colors.Green);

而是试图弄清楚如何设置前景色为禁用的按钮使我下了兔子洞。

我希望能够在不必使用XAML (like this approach)的情况下进行设置,因为我打算稍后提取这些渲染器。

回答

1

如果您可以编辑按钮的样式,或者将其定义在资源的某个位置,然后将其应用于您的按钮,即使是来自代码,也是最好的选择。

还有其他的方法,理论上更简单,可以从代码中获得。如果你看一下按钮的风格,你会看到一节禁用可视状态:

<VisualState x:Name="Disabled"> 
    <Storyboard> 
     <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Background" Storyboard.TargetName="RootGrid"> 
      <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlBackgroundBaseLowBrush}"/> 
     </ObjectAnimationUsingKeyFrames> 
     <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground" Storyboard.TargetName="ContentPresenter"> 
      <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlDisabledBaseMediumLowBrush}"/> 
     </ObjectAnimationUsingKeyFrames> 
     <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="BorderBrush" Storyboard.TargetName="ContentPresenter"> 
      <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlDisabledTransparentBrush}"/> 
     </ObjectAnimationUsingKeyFrames> 
    </Storyboard> 
</VisualState> 

你看,这是用它那个状态刷资源的名称。在代码中更改它们应该足以使所有禁用的按钮看起来像你想要的。尽管您需要记住,当用户更改主题并且您的应用程序被暂停时,这也会改变行为。

private void Button_Click(object sender, RoutedEventArgs e) 
{ 
    App.Current.Resources["SystemControlBackgroundBaseLowBrush"] = new SolidColorBrush(Colors.Yellow); // background 
    App.Current.Resources["SystemControlDisabledBaseMediumLowBrush"] = new SolidColorBrush(Colors.Red); // content 
    App.Current.Resources["SystemControlDisabledTransparentBrush"] = new SolidColorBrush(Colors.Green); // border 
}