Search code examples
c#winui-3

WinUI3: how to set disabled button background


So I'm adding buttons via code to the grid, when some button is clicked i want to disable it and set background color to green or other, background should be set only to that one clicked button. But no matter what disabled button have transparent background.

I've tried adding method to IsEnabledChanged event

button.IsEnabledChanged += (sender, e) =>
{
    button.Background = brush;
};

This is the only way I managed to change background when button is disabled, but for some reason it's not working every time. I've also tried to set "ButtonDisabledBackgroundThemeBrush" in code:

private void BottomGridButtonClick(object sender, RoutedEventArgs e)
{
    Button btn = ((Button)sender);

    btn.Resources.Add(new KeyValuePair<object, object>("ButtonDisabledBackgroundThemeBrush", new SolidColorBrush(Colors.Green)));
    btn.Resources["ButtonDisabledBackgroundThemeBrush"] = new SolidColorBrush(Colors.Green);

    ((Button)sender).IsEnabled = false;
}

Setting "ButtonDisabledBackgroundThemeBrush" in generic.xaml have no effect also.


Solution

  • You need to override the ButtonBackgroundDisabled resource:

    btn.Resources["ButtonBackgroundDisabled"] = new SolidColorBrush(Colors.Green);
    

    You can find this in DefaultButtonStyle in the generic.xaml.