简体   繁体   中英

How to bind button to control

I am new to WPF. I have a button on my mainwindow

<Button Grid.Row="1" x:Name="btnSelect" Command="{Binding SaveCommand}"   
      Content="Select" 
     IsEnabled="{Binding CanExec,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" 

and in myViewModel

    private bool _canExecute;
    private ICommand saveCommand;
    public MainWindow()
    {
        InitializeComponent();
        DataContext = this;
          CreateSaveCommand();

    }
   private void CreateSaveCommand()
    {
        this.saveCommand = new DelegateCommand<object>(this.OnSaveClick,    this.CanSaveExecute);
    }
    public ICommand SaveCommand
    {
        get { return this.saveCommand; }
    }
    private void OnSaveClick(object arg)
    {


    }
    private bool CanSaveExecute(object arg)
    {
        return CanExec;

    }

    public bool CanExec
    {

        get { return _canExecute; }
        set { _canExecute = value; OnPropertyChanged("CanExec"); }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    private void OnPropertyChanged(string p)
    {
        if (PropertyChanged == null)
            PropertyChanged(this, new PropertyChangedEventArgs(p));
    }

But the button always remain disabled..What am I missing ??

Your problem is in your implementation of the OnPropertyChanged method... at present, the event will only get called if it is null , which of course, would cause an Exception . Try this instead:

private void OnPropertyChanged(string p)
{
    if (PropertyChanged != null)
        PropertyChanged(this, new PropertyChangedEventArgs(p));
}

UPDATE >>>

Your Binding Path is also incorrect, but that would not stop it from working... it should be like this:

<Button Grid.Row="1" x:Name="btnSelect" Command="{Binding SaveCommand}"   
    Content="Select" />

Please note that ICommand.CanExecute does not have to be set to the IsEnabled property manually... the Framework will do that for us.

Bool的默认值为'False',因此您的CanExec返回'False'并且您的按钮被禁用。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM