我见过一个允许我在XAML中执行此操作的库,它根据用户是否在某个角色中设置控件的可见性: S:Authorization.RequiresRole = “系统管理员”
在我的数据库中使用该库需要一堆我现在不能真正做的编码。最终这就是我想知道的......
我已经从我的SPROC收到了经过身份验证的用户角色,并且它当前存储在我的App.xaml.cs中作为属性(对于最终解决方案来说不是必需的,现在只是FYI)。我想创建一个属性(依赖属性?附加属性?),它允许我说出与其他库非常相似的东西:RequiresRole =“Admin”,如果用户不在Admin角色中,则会崩溃可见性。有人能指出我正确的方向吗?
修改 构建授权类后,我收到以下错误: “XML Namespace clr-namespace中的'HyperlinkButton'类型不存在'RequiredRole'属性:TSMVVM.Authorization”
我正在尝试添加此xaml:
<HyperlinkButton x:Name="lnkSiteParameterDefinitions"
Style="{StaticResource LinkStyle}"
Tag="SiteParameterDefinitions"
Content="Site Parameter Definitions"
Command="{Binding NavigateCommand}"
s:Authorization.RequiredRole="Admin"
CommandParameter="{Binding Tag, ElementName=lnkSiteParameterDefinitions}"/>
当我开始输入s:Authorization.RequiredRole =“Admin”时,intellisense选择了它。我尝试将typeof(string)和typeof(ownerclass)设置为HyperlinkButton以查看是否有帮助,但事实并非如此。有什么想法吗?
答案 0 :(得分:4)
附属财产是实施它的方式。你应该定义一个这样的属性:
public class Authorization
{
#region Attached DP registration
public static string GetRequiredRole(UIElement obj)
{
return (string)obj.GetValue(RequiredRoleProperty);
}
public static void SetRequiredRole(UIElement obj, string value)
{
obj.SetValue(RequiredRoleProperty, value);
}
#endregion
// Using a DependencyProperty as the backing store for RequiredRole. This enables animation, styling, binding, etc...
public static readonly DependencyProperty RequiredRoleProperty =
DependencyProperty.RegisterAttached("RequiredRole", typeof(string), typeof(Authorization), new PropertyMetadata(RequiredRole_Callback));
// This callback will be invoked when some control will receive a value for your 'RequiredRole' property
private static void RequiredRole_Callback(DependencyObject source, DependencyPropertyChangedEventArgs e)
{
var uiElement = (UIElement) source;
RecalculateControlVisibility(uiElement);
// also this class should subscribe somehow to role changes and update all control's visibility after role being changed
}
private static void RecalculateControlVisibility(UIElement control)
{
//Authorization.UserHasRole() - is your code to check roles
if (Authentication.UserHasRole(GetRequiredRole(control)))
control.Visibility = Visibility.Visible;
else
control.Visibility = Visibility.Collapsed;
}
}
PS:已经注意到你在询问Silverlight时已经太晚了。虽然我相信它的工作方式与此相同,但我只在WPF上尝试过。