简体   繁体   中英

How to unlock button function after pressing a button?

I tried to get my hands on WPF. My question is, whether there is a way to unlock the buttons (2.) after pressing the button login (1.). Basically I want an error to pop up if someone is pressing eg the Excel -Button as long as he's not logged in.

该窗口显示登录表单以及侧面菜单。

One way to play around with button enabling and disabling in WPF, is to use RoutedCommands instead of click_events. There are 4 steps for that:

1) Assign a static resource for every button you are using, as a resource on a parent UI element. Assuming for example you have a Grid as a parent to these buttons:

<Grid>
  <Grid.Resources>
      <RoutedCommand x:Key="cmdButtonCommandName" />
  </Grid.Resources>
  ...
</Grid>

2) Define a CommandBinding for each Command, under the same parent. The code becomes:

<Grid>
  <Grid.Resources>
      <RoutedCommand x:Key="cmdButtonCommandName" />
  </Grid.Resources>
  <Grid.CommandBindings>
        <CommandBinding CanExecute="CmdButtonCommandName_CanExecute"
                    Command="{StaticResource cmdButtonCommandName}"
                    Executed="CmdButtonCommandName_Executed"/>
  </Grid.CommandBindings>
...
</Grid>

3) Assign the Static resource as the Command of the Button you want:

<Button Content="Excel" Command="{StaticResource cmdButtonCommandName}"/>

4) In the code behind add the methods CmdButtonCommandName_CanExecute and CmdButtonCommandName_Executed

private void CmdButtonCommandName_CanExecute(object sender, CanExecuteRoutedEventArgs e)
    {
        e.CanExecute = true;
    }

    private void CmdButtonCommandName_Executed(object sender, ExecutedRoutedEventArgs e)
    {
        ...
    }

There you can set e.CanExecute which defines whether the button is enabled or disabled...

So, to answer your question... If you want to unlock (enable) buttonA after buttonB is pressed, you set a boolean flag isButtonBpressed equal to true in the end of the method buttonB_Executed, and then in the buttonA_CanExecute method you set e.CanExcute = isButtonBpressed;

It might seem complicated in the beginning, but if you get the hang of it, is quite straightforward.

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