【问题标题】:Set the foreground color for a disabled button in code (UWP)在代码中设置禁用按钮的前景色 (UWP)
【发布时间】:2016-10-10 17:16:58
【问题描述】:

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

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

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

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

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

【问题讨论】:

    标签: c# xamarin xamarin.forms uwp custom-renderer


    【解决方案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
    }
    

    【讨论】:

      猜你喜欢
      • 2021-04-28
      • 1970-01-01
      • 2013-06-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多