How to dynamically enable a button in WPF Forms with C#?

Lakshmanan B 81 Reputation points
2024-08-07T14:56:55.13+00:00

Hi, I am new to WPF but not to C#. I am working on a application where I have several buttons and I need to change the state of the buttons based on certain conditions.

For instance, I have this "Add User" button which will be enabled only if the Signed in user is an Admin, if not the button is disabled.

In my XAML, I have the following code for the Add User button:

<UserControl x:Class="sampleProject.controls.controlOptionsMenu"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:local="clr-namespace:sampleProject.controls"
             mc:Ignorable="d" Height="79" Width="800">
    <Grid Background="#FFEDEDED" Height="80">
        <Button x:Name="addUserButton" Width="66" Margin="10,0,0,0" BorderThickness="0,0,0,0" HorizontalAlignment="Left" VerticalAlignment="Center" Height="58" IsEnabled="True">
            <Button.Effect>
                <DropShadowEffect ShadowDepth="3" BlurRadius="5" Color="LightGray"/>
            </Button.Effect>
            <StackPanel Width="62" Height="56">
                <Image Source="/resources/add_user_icon.png" Height="32" Width="32"/>
                <Label Content="Add User" Height="23" Width="60" VerticalAlignment="Center" HorizontalAlignment="Center"/>
            </StackPanel>
        </Button>
    </Grid>
</UserControl>

In my CS code, I have the following condition:

            if(isUserAdmin)
            {
                addUserButton.IsEnabled = true;
            } else
            {
                addUserButton.IsEnabled = false;
            }

When, I execute the button state does not change. Can someone help with this? Thanks In Advance.!

Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,751 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,801 questions
XAML
XAML
A language based on Extensible Markup Language (XML) that enables developers to specify a hierarchy of objects with a set of properties and logic.
800 questions
{count} votes

Accepted answer
  1. Viorel 116.4K Reputation points
    2024-08-08T08:38:06.47+00:00

    Instead of creating an unused object with new, you should use the control that is already inserted to MainWindow. The XAML of window that contains your user control usually looks like this:

     <local:controlOptionsMenu x:Name="ControlOptionsMenu" . . . />
    

    Specify the x:Name attribute, and use this code:

    ControlOptionsMenu.getIfUserIsAdmin( isUserAdmin );
    

    If it does not work, then show details about the usage of your user control in the main window.

    1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Hongrui Yu-MSFT 1,515 Reputation points Microsoft Vendor
    2024-08-08T03:50:47.0166667+00:00

    Hi,@Lakshmanan B. Welcome to Microsoft Q&A. 

    After testing, your cs code could successfully enable or disable the button. Please make sure that your cs code is executed. Below are the test code and steps.

    
    <Grid Background="#FFEDEDED" Height="80">
    
        <Grid.ColumnDefinitions>
    
            <ColumnDefinition/>
    
            <ColumnDefinition/>
    
        </Grid.ColumnDefinitions>
    
        <Button IsEnabled="True" Click="addUserButton_Click" x:Name="addUserButton" Width="66" Margin="10,0,0,0" BorderThickness="0,0,0,0" HorizontalAlignment="Left" VerticalAlignment="Center" Height="58" >
    
            <Button.Effect>
    
                <DropShadowEffect ShadowDepth="3" BlurRadius="5" Color="LightGray"/>
    
            </Button.Effect>
    
            <StackPanel Width="62" Height="56">
    
                <Image Source="/resources/add_user_icon.png" Height="32" Width="32"/>
    
                <Label Content="Add User" Height="23" Width="60" VerticalAlignment="Center" HorizontalAlignment="Center"/>
    
            </StackPanel>
    
        </Button>
    
        <Button Grid.Column="1" Width="120" Height="58" Margin="10,0,0,0" Content="Change IsUserAdmin" Click="Button_Click" HorizontalAlignment="Left"></Button>
    
    </Grid>
    
    
    
    public partial class controlOptionsMenu : UserControl
    
    {
    
        public bool isUserAdmin;
    
        public controlOptionsMenu()
    
        {
    
            InitializeComponent();
    
            isUserAdmin = true;
    
        }
    
     
    
     
    
        private void addUserButton_Click(object sender, RoutedEventArgs e)
    
        {
    
            MessageBox.Show("AAA");
    
        }
    
     
    
        private void Button_Click(object sender, RoutedEventArgs e)
    
        {
    
            isUserAdmin = !isUserAdmin;
    
            if (isUserAdmin)
    
            {
    
                addUserButton.IsEnabled = true;
    
            }
    
            else
    
            {
    
                addUserButton.IsEnabled = false;
    
            }
    
        }
    
    }
    
    

    When you click Change IsUserAdmin button, you could enable or disable the button.When the enabled button is clicked, a pop-up window will pop up

     

    Optimization

    You could directly bind isUserAdmin to IsEnabled of Button, so that Button could be enabled or disabled in real time according to isUserAdmin. The reference code is as follows.

    Change IsEnabled="True" to IsEnabled="{Binding IsUserAdmin}"

    
    <Grid Background="#FFEDEDED" Height="80">
    
        <Grid.ColumnDefinitions>
    
            <ColumnDefinition/>
    
            <ColumnDefinition/>
    
        </Grid.ColumnDefinitions>
    
        <Button IsEnabled="{Binding IsUserAdmin}" Click="addUserButton_Click" x:Name="addUserButton" Width="66" Margin="10,0,0,0" BorderThickness="0,0,0,0" HorizontalAlignment="Left" VerticalAlignment="Center" Height="58" >
    
            <Button.Effect>
    
                <DropShadowEffect ShadowDepth="3" BlurRadius="5" Color="LightGray"/>
    
            </Button.Effect>
    
            <StackPanel Width="62" Height="56">
    
                <Image Source="/resources/add_user_icon.png " Height="32" Width="32"/>
    
                <Label Content="Add User" Height="23" Width="60" VerticalAlignment="Center" HorizontalAlignment="Center"/>
    
            </StackPanel>
    
        </Button>
    
        <Button Grid.Column="1" Width="120" Height="58" Margin="10,0,0,0" Content="Change IsUserAdmin" Click="Button_Click" HorizontalAlignment="Left"></Button></Grid>
    
    
    
    public partial class controlOptionsMenu : UserControl,INotifyPropertyChanged
    
    {
    
        private bool isUserAdmin;
    
        public bool IsUserAdmin
    
        {
    
            get { return isUserAdmin; }
    
            set { isUserAdmin = value; OnPropertyChanged("IsUserAdmin"); }
    
        }
    
        public controlOptionsMenu()
    
        {
    
            InitializeComponent(); 
    
            this.DataContext = this;
    
     
    
            IsUserAdmin = true;
    
     
    
        }
    
     
    
        public event PropertyChangedEventHandler PropertyChanged;
    
     
    
        public void OnPropertyChanged(string propertyName)
    
        {
    
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    
        }
    
     
    
        private void addUserButton_Click(object sender, RoutedEventArgs e)
    
        {
    
            MessageBox.Show("AAA");
    
        }
    
     
    
        private void Button_Click(object sender, RoutedEventArgs e)
    
        {
    
            IsUserAdmin = !IsUserAdmin;
    
        }
    
    }
    
    

    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.