如果您可以編輯按鈕的樣式,或者將其定義在資源的某個位置,然後將其應用於您的按鈕,即使是來自代碼,也是最好的選擇。
還有其他的方法,理論上更簡單,可以從代碼中獲得。如果你看一下按鈕的風格,你會看到一節禁用可視狀態:
<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
}