首页 > 代码库 > 权限控制
权限控制
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Diagnostics;
namespace WpfBrowserApplication1
{
/// <summary>
/// Page1.xaml 的交互逻辑
/// </summary>
public partial class Page1 : Page
{
public Page1()
{
InitializeComponent();
}
private void Page_Loaded(object sender, RoutedEventArgs e)
{
ResourcePermission resourcePer = new ResourcePermission() { Name="tb3",Avaliable=0};
object obj = PrintLogicalTree(this, resourcePer);
if (obj is TextBlock)
{
TextBlock btn = obj as TextBlock;
MessageBox.Show(btn.Text);
}
else if (obj is TextBox)
{
TextBox tb = obj as TextBox;
MessageBox.Show(tb.Text);
}
else if (obj is Button)
{
Button btn = obj as Button;
btn.IsEnabled = false;
}
}
object PrintLogicalTree(object obj, ResourcePermission resourcePermission)
{
if (obj == null)
return null;
if (obj is TextBlock)
{
TextBlock btn = obj as TextBlock;
if (resourcePermission.Name.Equals(btn.Name))
{
if (resourcePermission.Avaliable==0)
btn.Visibility = Visibility.Collapsed;
else
btn.Visibility = Visibility.Visible;
return btn;
}
}
else if (obj is TextBox)
{
TextBox tb = obj as TextBox;
if (resourcePermission.Equals(tb.Name))
return tb;
}
else if (obj is Button)
{
Button btn = obj as Button;
if (resourcePermission.Equals(btn.Name))
return btn;
}
//如果不是DependencyObject,如string等类型
//if (!(obj is DependencyObject))
// return null;
object result = null;
//递归打印逻辑树
foreach (object child in LogicalTreeHelper.GetChildren(
obj as DependencyObject))
{
if (child is DependencyObject)
{
result = PrintLogicalTree(child, resourcePermission);
}
if (result != null)
break;
}
return result;
}
enum ResourceTypeEnum
{
Button = 1,
TextBlock = 2,
Textbox=3,
Combox=4,
}
class ResourcePermission
{
public string Name { get; set; }
public Int16 Avaliable { get; set; }
}
DependencyObject PrintVisualTree(DependencyObject obj,string value)
{
if (obj == null)
return null;
//打印空格,方便查看
Debug.WriteLine(obj);
if (obj is TextBlock)
{
TextBlock tb = obj as TextBlock;
if(value.Equals(tb.Name))
return tb;
}
// 递归打印视觉树
DependencyObject result = null;
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
{
result= PrintVisualTree(VisualTreeHelper.GetChild(obj, i),value);
if (result != null)
break;
}
return result;
}
}
}
权限控制