Home > Software engineering >  Buttons only for admin role
Buttons only for admin role

Time:12-21

I want to make regular button from wpf form and cell button from datagrid visible only for admin.

Button from DataGrid

/DataGridTemplateColumn>
                <DataGridTemplateColumn Header="Connect">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <Button Content="Add room" Name="addRoomButton" Click="addRoomButton_Click"></Button>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>

So im taking user from db, and pass this parameter into main window. Is there any ways to do this correctly?

My WPF windows consturctor:

public ChatWindow(string currentUser, bool isAdmin)
    {
        InitializeComponent();

        Username = currentUser;      
        IsAdmin= isAdmin;

        connection = new HubConnectionBuilder()
        .WithUrl("https://localhost:7195/chat")
        .WithAutomaticReconnect()
        .Build();           
    }

CodePudding user response:

Assuming that IsAdmin is a public property of the parent window, you could use a Style with a DataTrigger that binds to it and sets the Visibility property of the Button accordingly:

<Button Content="Add room" Name="addRoomButton" Click="addRoomButton_Click">
    <Button.Style>
        <Style TargetType="Button">
            <Setter Property="Visibility" Value="Collapsed" />
            <Style.Triggers>
                <DataTrigger Binding="{Binding IsAdmin, RelativeSource={RelativeSource AncestorType=Window}}" Value="True">
                    <Setter Property="Visibility" Value="Visible" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Button.Style>
</Button>
  • Related