2011-02-11 90 views
2

我见过一个库,它允许我在我的XAML中执行此操作,它根据用户是否在角色中设置控件的可见性: s:Authorization.RequiresRole =“Admin “自定义XAML属性

在我的数据库中使用该库需要一堆我现在无法真正完成的编码。最终这是我想知道的...

我已经从我的SPROC收到认证用户角色,并且它当前作为属性存储在我的App.xaml.cs中(对于最终解决方案不需要,仅供参考现在)。我想创建一个属性(依赖项属性?附加属性?),它允许我说出与其他库非常相似的内容:RequiresRole =“Admin”,如果用户不在Admin角色中,将会崩溃可见性。任何人都可以在正确的方向指向我吗?

编辑 建立授权下课后,我得到以下错误: “属性‘RequiredRole’不就在XML命名空间CLR的命名空间中的类型‘HyperlinkBut​​ton’存在: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 = “管理”,智能感知把它捡起来。我尝试将typeof(string)和typeof(ownerclass)设置为HyperlinkBut​​ton,以查看是否有帮助,但没有。有什么想法吗?

回答

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上尝试过。

+0

感谢您的回应!这看起来不错,但我有几个关于实现的问题。 1)typeof(ownerclass) - 我将它设置为授权,但我不确定这是否正确。 2)新的UIPropertyMetadata ...与新的PropertyMetadata相同吗? UIPropertyMetadata不能解决我的问题。 3)我创建了UserHasRole方法,并简单地返回true,如果App.Role.ToLower()与传入的role.ToLower()相同。听起来对吗? 4)为我的OP添加了一个编辑,因为我在构建时出错。 – 2011-02-11 23:56:45