2016-06-09 70 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 
}