1

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

更改活动按钮的颜色非常简单

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

但是试图弄清楚如何为禁用的按钮设置前景色让我陷入了困境。

我希望能够在不必使用 XAML (如这种方法)的情况下进行设置,因为我计划稍后提取这些渲染器。

4

1 回答 1

3

最好的办法是您可以编辑按钮的样式,或在资源中的某个位置定义它,然后将其应用到您的按钮,甚至是从代码中。

还有其他方法,理论上更简单并且可以从代码中获得。如果您查看按钮的样式,您将看到禁用视觉状态的部分:

<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
}
于 2016-06-10T05:11:12.933 回答