You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在WPF后台C#代码中为管理员/超级管理员启用TextBox?

修正TextBox权限控制逻辑问题

我有一个名为txtWeighbridgeWeight的TextBox,需求是:

  • 仅当管理员和超级管理员登录后,才启用该TextBox
  • 仅在捕获卡车信息时允许编辑重量值
    但当前代码逻辑未按预期生效,需要修正逻辑实现需求。

XAML标记

<TextBox 
    VerticalAlignment="Center" Foreground="Black" Background="White"
    Width="268" FontWeight="SemiBold" FontSize="36" 
    TextAlignment="Right" Height="55" Margin="1,1,1,1" 
    Padding="2,2,2,2" HorizontalAlignment="Center" x:Name="txtWeighbridgeWeight" 
    TextChanged="txtWeighbridgeWeight_TextChanged"/>

C#后台代码

public MainWindow()
{
    try
    {
        InitializeComponent();

        if (System.Deployment.Application.ApplicationDeployment.IsNetworkDeployed)
        {
            lblPath.Content = System.Deployment.Application.ApplicationDeployment.CurrentDeployment.UpdateLocation.AbsolutePath;
        }

        dispatcherTimer = new DispatcherTimer();
        dispatcherTimer.Tick += dispatcherTimer_Tick;
        dispatcherTimer.Interval = new TimeSpan(0, 0, 0, 0, 1);
        dispatcherTimer.Start();
        panelWidth = sidepanel1.Width;
        panelWidth = sidePanel.Width;

        User user = new User();
        LabAssistant user1 = new LabAssistant();

        if (Properties.Settings.Default.Quality == "Q")
        {
            user1 = Managers.ManageLabAssistant.GetUserByPK(Properties.Settings.Default.LoggedInUserID);
            txtLoggedInUser.Text = user1.UserName;
        }
        else
        {
            user = Managers.UserManager.GetUserByPK(Properties.Settings.Default.LoggedInUserID);
            txtLoggedInUser.Text = user.Username;
        }

        txtStation.Text = Properties.Settings.Default.Station;

        if (System.Deployment.Application.ApplicationDeployment.IsNetworkDeployed)
        {
            this.txtVersion.Text = System.Deployment.Application.ApplicationDeployment.CurrentDeployment.CurrentVersion.ToString();
        }

        var menuWB = new List<SubItem>();
        menuWB.Add(new SubItem("Raw Material", new UCRaw_Material()));
        menuWB.Add(new SubItem("Finished Product", new UCFinishedProduct()));
        var item0 = new ItemMenu("Weighbridge", menuWB, PackIconKind.Truck);

        var menuReports = new List<SubItem>();
        menuReports.Add(new SubItem("Customer", new UCManageCustomer()));
        menuReports.Add(new SubItem("Client", new UCManageClients()));
        menuReports.Add(new SubItem("Bin", new UCManageBin()));
        menuReports.Add(new SubItem("Drivers", new UCManageDriver()));
        menuReports.Add(new SubItem("Farm", new UCManageFarm()));
        menuReports.Add(new SubItem("Material", new UCManageMaterial()));
        menuReports.Add(new SubItem("Product", new UCManageProduct()));
        menuReports.Add(new SubItem("Supplier", new UCManageSupplier()));
        menuReports.Add(new SubItem("Vehicle", new UCManageVehicle()));
        menuReports.Add(new SubItem("Batch Material", new UCManageBatchMaterial()));
        menuReports.Add(new SubItem("Feed Production Schedule", new UCFeedproductionSchedule()));
        menuReports.Add(new SubItem("Feed Production Requirements", new UCOrderRequirements()));

        menuReports.Add(new SubItem("Batch Feed Format", new UCManageBatchFeedFormat()));
        menuReports.Add(new SubItem("Status", new UCStatusScreen()));
        menuReports.Add(new SubItem("Recipes", new UCManageRecipe()));
        menuReports.Add(new SubItem("Batch Recipes", new UCManageBatchRecipe()));
        menuReports.Add(new SubItem("Configuration", new UCConfigScreen()));
        menuReports.Add(new SubItem("Reports", new UCManageReports()));

        var item2 = new ItemMenu("Administration", menuReports, PackIconKind.AccountCog);

        var menuQC = new List<SubItem>();
        menuQC.Add(new SubItem("Crumble", new UCManageQcCrumbleData()));
        menuQC.Add(new SubItem("Pellet", new UCManagePelletData()));
        menuQC.Add(new SubItem("Grist", new UCManageGrist()));
        menuQC.Add(new SubItem("Reports", new UCQualityReports()));

        var item3 = new ItemMenu("Quality Control", menuQC, PackIconKind.Controller);

        if (user.UserTypeID == Convert.ToInt32(Enum.UserType.Admin))
        {
            Menu.Children.Add(new UserControlMenuItem(item0, this));
            Menu.Children.Add(new UserControlMenuItem(item2, this));
            Menu.Children.Add(new UserControlMenuItem(item3, this));
            menuQC.Add(new SubItem("Users", new UCLabAssistant()));
            menuQC.Add(new SubItem("Supervisor", new UCQCManageSupervisor()));
            menuWB.Add(new SubItem("Reports", new UCManageSupervisorReports()));
            txtWeighbridgeWeight.IsEnabled = true; // this not working
        }

        if (user.UserTypeID == Convert.ToInt32(Enum.UserType.Admin))
        {
            txtWeighbridgeWeight.IsEnabled = true;// this is not working, cant edit any value when page is loaded as an admin and Super-User
            txtWeighbridgeWeight.IsReadOnly = false;
        }

        if (user.UserTypeID == Convert.ToInt32(Enum.UserType.SuperUser))
        {
            Menu.Children.Add(new UserControlMenuItem(item0, this));
            Menu.Children.Add(new UserControlMenuItem(item2, this));
            Menu.Children.Add(new UserControlMenuItem(item3, this));
            menuReports.Add(new SubItem("Users", new UCManageUsers()));
            menuQC.Add(new SubItem("Users", new UCLabAssistant()));
            menuQC.Add(new SubItem("Supervisor", new UCQCManageSupervisor()));
            menuWB.Add(new SubItem("Reports", new UCManageSupervisorReports()));
            txtWeighbridgeWeight.IsEnabled = true; // this gets called first
        } 

        if (user.UserTypeID == Convert.ToInt32(Enum.UserType.SuperUser))
        {
            txtWeighbridgeWeight.IsEnabled = true; // here is not working
        }

        if (user.UserTypeID == Convert.ToInt32(Enum.UserType.User))
        {
            Menu.Children.Add(new UserControlMenuItem(item0, this));
        }

        if (user.UserTypeID == Convert.ToInt32(Enum.UserType.Supervisor))
        {
            Menu.Children.Add(new UserControlMenuItem(item0, this));
            menuWB.Add(new SubItem("Reports", new UCManageSupervisorReports()));
        }

        // inventory controller logic implemented
        if (user.UserTypeID == Convert.ToInt32(Enum.UserType.InventController))
        {
            Menu.Children.Add(new UserControlMenuItem(item0, this));
            menuWB.Add(new SubItem("Reports", new UCManageReports()));
        }
        else
        {
            txtWeighbridgeWeight.IsReadOnly = true;
        }

        if (user1.UserLevelID == Convert.ToInt32(Enum.UserType.Admin))
        {
            Menu.Children.Add(new UserControlMenuItem(item3, this));
            menuQC.Add(new SubItem("Users", new UCLabAssistant()));
        }
        else
        {
            // txtWeighbridgeWeight.IsReadOnly = true;
        }

        if (user1.UserLevelID == Convert.ToInt32(Enum.UserType.User))
        {
            Menu.Children.Add(new UserControlMenuItem(item3, this));
        }
        else
        {
            txtWeighbridgeWeight.IsReadOnly = true; 
        }

        if (user.UserTypeID == Convert.ToInt32(Enum.UserType.Admin) || user.UserTypeID == Convert.ToInt32(Enum.UserType.User)|| user.UserTypeID == Convert.ToInt32(Enum.UserType.Supervisor) || user.UserTypeID == Convert.ToInt32(Enum.UserType.SuperUser) || user.UserTypeID == Convert.ToInt32(Enum.UserType.InventController))
        {
            if (Properties.Settings.Default.Station.ToUpper() != "BOTTOM")
            {
                UCRaw_Material uc = new UCRaw_Material();

                SwitchScreen(uc);
            }
            else
            {
                UCFinishedProduct uc = new UCFinishedProduct();
                SwitchScreen(uc);
            }
        }

        if (user1.UserLevelID == Convert.ToInt32(Enum.UserType.Admin) || user1.UserLevelID == Convert.ToInt32(Enum.UserType.User))
        {
            if (Properties.Settings.Default.Station.ToUpper() != "BOTTOM")
            {
                UCManageQcCrumbleData uc = new UCManageQcCrumbleData();
                SwitchScreen(uc);
            }
            else
            {
                UCManagePelletData uc = new UCManagePelletData();
                SwitchScreen(uc);
            }
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message + "/n" + ex.InnerException);
    }
}

问题分析

  1. 逻辑冗余且冲突:多次重复判断管理员/超级管理员权限,后续的else分支(如InventController、LabAssistant的else)会强制设置IsReadOnly = true,直接覆盖之前的权限设置
  2. 未区分场景:没有针对"捕获卡车信息"的页面单独控制编辑权限,无法实现仅该场景允许编辑的需求

修正方案

1. 重构权限判断逻辑,避免覆盖

将重复的权限判断合并,初始化时默认禁用TextBox,仅对管理员/超级管理员开放基础权限:

// 初始化默认禁用
txtWeighbridgeWeight.IsEnabled = false;
txtWeighbridgeWeight.IsReadOnly = true;

// 统一判断管理员/超级管理员
bool isAdminOrSuper = user.UserTypeID == Convert.ToInt32(Enum.UserType.Admin) 
                      || user.UserTypeID == Convert.ToInt32(Enum.UserType.SuperUser);

if (isAdminOrSuper)
{
    txtWeighbridgeWeight.IsEnabled = true;
    txtWeighbridgeWeight.IsReadOnly = false;
    
    // 菜单逻辑保留
    Menu.Children.Add(new UserControlMenuItem(item0, this));
    Menu.Children.Add(new UserControlMenuItem(item2, this));
    Menu.Children.Add(new UserControlMenuItem(item3, this));
    menuQC.Add(new SubItem("Users", new UCLabAssistant()));
    menuQC.Add(new SubItem("Supervisor", new UCQCManageSupervisor()));
    menuWB.Add(new SubItem("Reports", new UCManageSupervisorReports()));
    
    // 超级管理员额外菜单
    if(user.UserTypeID == Convert.ToInt32(Enum.UserType.SuperUser))
    {
        menuReports.Add(new SubItem("Users", new UCManageUsers()));
    }
}

2. 移除会覆盖权限的冗余else分支

删除以下代码块,避免强制重置IsReadOnly:

// 移除InventController的else分支
// else
// {
//     txtWeighbridgeWeight.IsReadOnly = true;
// }

// 移除LabAssistant的else分支
// else
// {
//     txtWeighbridgeWeight.IsReadOnly = true; 
// }

3. 添加场景化编辑控制

在页面切换方法SwitchScreen中,判断当前是否为卡车信息捕获页面(UCRaw_Material/UCFinishedProduct),仅在该场景允许管理员/超级管理员编辑:

public void SwitchScreen(UserControl uc)
{
    // 原有页面切换逻辑
    mainContent.Children.Clear();
    mainContent.Children.Add(uc);

    bool isTruckCapture = uc is UCRaw_Material || uc is UCFinishedProduct;
    bool isAdminOrSuper = user.UserTypeID == Convert.ToInt32(Enum.UserType.Admin) 
                          || user.UserTypeID == Convert.ToInt32(Enum.UserType.SuperUser);

    // 仅管理员/超级管理员在卡车捕获页面时可编辑
    txtWeighbridgeWeight.IsReadOnly = !(isAdminOrSuper && isTruckCapture);
    // 启用状态仅由管理员/超级管理员控制
    txtWeighbridgeWeight.IsEnabled = isAdminOrSuper;
}

内容的提问来源于stack exchange,提问作者thrue2023

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 09:47:01