简体   繁体   中英

Hiding and Showing menu (tool) bar based on user access level

I am creating a desktop application using WPF c# in Visual Studio 2010 express. I have created a menu bar which I would like to display certain elements depending on user access level. I can set the menu visibility to Hidden as default but finding it difficult to set the visitbility to Visible thereafter once a successful sign in has been made. Below is the sample of the 'xaml' code and the c# code.

'XAML code'

<Menu Name="MenuBar" VerticalAlignment="Top" Width="Auto" Margin="0,0,0,389">
    <MenuItem Header="_Maintenance" Margin="2,0,0,2" Width="Auto"
              Visibility="hidden" Click="MenuItem_Click">
        <MenuItem Header="Customer Maintenance"/>
        <MenuItem Header="Staff Maintenance"/>
        <MenuItem Header="User Maintenance"/>
        <MenuItem Header="Item Maintenance"/>
        <MenuItem Header="Standing Maintenance"/>
    </MenuItem>
</Menu>

My attempt on the 'C# code'

public MainWindow()
{
    InitializeComponent();
}

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    MenuBar.Visibility="Visible";

    //Load and display sign in screen
    App1 app = new App1();
    app.LoadSignIn();
}

Errors I'm facing are:

Cannot implicitly convert type 'string' to 'System.Windows.Visibility'

You'll want to bind to a Style Trigger to get this behavior, like so (excerpted from one of the links below, modified to match your supplied xaml):

<Window.Resources>
  <Style x:Key="VisibleWhenUserAllowedAccess" TargetType="MenuItem">
      <Style.Triggers>
          <DataTrigger Binding="{Binding IsUserAllowedAccess}" Value="False">
              <Setter Property="Visibility" Value="Hidden"/>
          </DataTrigger>
    </Style.Triggers>
  </Style>

<Menu Name="MenuBar" VerticalAlignment="Top" Width="Auto" Margin="0,0,0,389">
    <MenuItem Header="_Maintenance" Margin="2,0,0,2" Width="Auto"
          Click="MenuItem_Click" 
          Style="{StaticResource VisibleWhenFileIsOpen}">
        <MenuItem Header="Customer Maintenance"/>
        <MenuItem Header="Staff Maintenance"/>
        <MenuItem Header="User Maintenance"/>
        <MenuItem Header="Item Maintenance"/>
        <MenuItem Header="Standing Maintenance"/>
    </MenuItem>
</Menu>

More reading on changing visibility of menus in WPF in these two links:

WPF UserControl Context Menu Visibility Binding

http://www.codeproject.com/Articles/37848/WPF-Data-Bound-Menus

Your code

MenuBar.Visibility="Visible";

is not correct.

Visibility is an enum type instead of string. You can set it like this:

MenuBar.Visibility =Visibility.Visible.

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