How to set Checkbox value from code?

B M-A 361 Reputation points
2023-02-16T14:34:06.2466667+00:00

Hello,

I want to set checkbox value from the code (WPF) but without success.

My code is something like this:

public Main(bool GrupMember)
        {
            InitializeComponent();
            bool idGrup =  true ;
                 
            checkbox.IsChecked = idGrup ;
            MessageBox.Show(idGrup.ToString());
 }
Developer technologies | Windows Presentation Foundation
Developer technologies | C#
Developer technologies | 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.


Answer accepted by question author
Hui Liu-MSFT 48,726 Reputation points Microsoft External Staff
2023-02-24T08:40:21.7233333+00:00

You could refer to the following code.

 <Window.DataContext>
        <local:ViewModel/>
    </Window.DataContext>
    <Grid>
       
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition/>
        </Grid.RowDefinitions>
      
        <StackPanel>
            <StackPanel Orientation="Horizontal" >
                <TextBlock Height="23"  Name="textBlock1" Text="name" VerticalAlignment="Top" Width="100" />
                <TextBox Height="23"  Name="textBoxName" Text="{Binding NameText}" VerticalAlignment="Top" Width="247" />
            </StackPanel>
            <StackPanel Orientation="Horizontal">
                <TextBlock Height="23"  Name="textBlock2" Text="Password" VerticalAlignment="Top" Width="100" />
                <PasswordBox Height="23" Name="passwordBox1" PasswordChanged="OnPasswordChanged" VerticalAlignment="Top" Width="247" />
            </StackPanel>
            <Button Content="Login" Height="23"  Name="button1" VerticalAlignment="Top" Width="104" Command="{Binding LoginCommand}"  CommandParameter="{Binding}" />
            <TextBlock Height="23"  Name ="errormessage1"  Width="247"  OpacityMask="Crimson" Foreground="#FFE5572C"  />
        </StackPanel>
        <StackPanel Grid.Row="1">
            <TextBlock x:Name="CurrentUser" Background="AliceBlue"  Text="{Binding CurrentUser.Name}" Height=" 50"/>
            <CheckBox x:Name="cb" IsChecked="{Binding CurrentUser.IsAdmin}"  Content="IsAdmin" Width="100" Height="50">
                
            </CheckBox>

            <Menu DockPanel.Dock="Top" ItemsSource="{Binding MenuItemsView}">
                <Menu.ItemContainerStyle>
                    <Style TargetType="{x:Type MenuItem}">
                        <Setter Property="Command" Value="{Binding Command}" />
                    </Style>
                </Menu.ItemContainerStyle>
                <Menu.ItemTemplate>
                    <HierarchicalDataTemplate DataType="{x:Type local:MenuItemViewModel}" ItemsSource="{Binding Path=MenuItems}">
                        <TextBlock Text="{Binding Header}"/>
                    </HierarchicalDataTemplate>
                </Menu.ItemTemplate>
            </Menu>
        </StackPanel>
    </Grid>

 public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        private void OnPasswordChanged(
       object sender,
       RoutedEventArgs e)
        {
            Debug.WriteLine(passwordBox1.Password);
        }
    }
    public class ViewModel : INotifyPropertyChanged
    {
        public ObservableCollection<MenuItemViewModel> MenuItems { get; set; }

        private ICollectionView menuItemsView;

        public ICollectionView MenuItemsView
        {
            get { return menuItemsView; }
            set
            {
                menuItemsView = value;
                OnPropertyChanged("MenuItemsView");
            }
        }
        public string NameText { get; set; }
        public string PassWordText { get; set; }
        public MyCommand1 LoginCommand { get; private set; }
        public ObservableCollection<User> Users { get; set; }=new ObservableCollection<User>();
        public ViewModel()
        {
            MenuItems = new ObservableCollection<MenuItemViewModel>
            {
                new MenuItemViewModel { Header = "Alpha" ,Level=0 },
                new MenuItemViewModel { Header = "Beta",Level=1,
                    MenuItems = new ObservableCollection<MenuItemViewModel>
                        {
                            new MenuItemViewModel { Header = "Beta1",Level=1 },
                            new MenuItemViewModel { Header = "Beta2",Level=1,
                                MenuItems = new ObservableCollection<MenuItemViewModel>
                                {
                                    new MenuItemViewModel { Header = "Beta1a" ,Level=2},
                                    new MenuItemViewModel { Header = "Beta1b" ,Level=2}
                                }
                            },
                            new MenuItemViewModel { Header = "Beta3",Level=0 }
                        }
                },
                new MenuItemViewModel { Header = "Gamma",Level=1 }
            };
            menuItemsView = CollectionViewSource.GetDefaultView(MenuItems);
            MenuItemsView.Filter = Level_Filter;
            Users.Add(new User() { Id = 1, Name = "jack",  PassWord="123", IsAdmin = false });
            Users.Add(new User() { Id = 2, Name = "john", PassWord = "123", IsAdmin = true });
            Users.Add(new User() { Id = 1, Name = "jennie", PassWord = "123", IsAdmin = false });

            LoginCommand = new MyCommand1(Login);
        }

        private void Login(object state)
        {
            ViewModel vm = state as ViewModel;
            string name = vm.NameText;
            CurrentUser = GetUserByName(name);
        }
        public User GetUserByName(string name)
        {
            var keyValue = Users.FirstOrDefault(user => user.Name == name);
            
            User current = Users.Where(user => user.Name == name).FirstOrDefault();
           
            return current;
        }
        private User currentUser=new User ();
        public  User CurrentUser
        {
            get { return currentUser; }
            set { currentUser = value;
                OnPropertyChanged("CurrentUser");
                MenuItemsView.Refresh();
            }
        }
        private int AdminLevel = 1;
        private bool Level_Filter(object item)
        {
            if (CurrentUser.IsAdmin == false)
            {
                MenuItemViewModel customer = item as MenuItemViewModel;
                return customer.Level == AdminLevel;
            }
            else
            {
                MenuItemViewModel customer = item as MenuItemViewModel;
                return customer.Level != AdminLevel;
            }
            return false;
        }

     
        public event PropertyChangedEventHandler PropertyChanged;
        protected void OnPropertyChanged([CallerMemberName] string name = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
        }
    }

   
   
   
    public class User
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string PassWord { get; set; }
        public bool IsAdmin { get; set; } 
    }


    public class MenuItemViewModel
    {
        public string Header { get; set; }
        public ObservableCollection<MenuItemViewModel> MenuItems { get; set; }
        public int Level { get; set; }
        private readonly ICommand _command;

        public MenuItemViewModel()
        {
            _command = new MyCommand(Execute);
        }
        public ICommand Command
        {
            get
            {
                return _command;
            }
        }
        private void Execute()
        {
            MessageBox.Show("Clicked at " + Header);
        }
    }

    public class MyCommand1 : ICommand
    {
        public event EventHandler CanExecuteChanged;
        private Action<object> _execute;
        public MyCommand1(Action<object> execute) => _execute = execute;
        public bool CanExecute(object parameter) => true;
        public void Execute(object parameter) => _execute.Invoke(parameter);
    }
    public class MyCommand : ICommand
    {
        private readonly Action _action;

        public MyCommand(Action action)
        {
            _action = action;
        }

        public void Execute(object o)
        {
            _action();
        }

        public bool CanExecute(object o)
        {
            return true;
        }

        public event EventHandler CanExecuteChanged
        {
            add { }
            remove { }
        }
    }

The result:

211


If the response is helpful, please click "Accept Answer" and upvote it.

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.

Was this answer helpful?

2 people found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

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