2011-02-11 102 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