我們使用依賴屬性確定的控制可視性。我們與我們的授權庫協同工作。因此,在我們的XAML,代碼看起來是這樣的:
<ListBoxItem x:Name="About"
Content="About Us"
AuthLib:Authorization.Visibility="WebUser"
Margin="10,5,10,5" />
<ListBoxItem x:Name="Accounting"
Content="Work Order Acct"
AuthLib:Authorization.Visibility="Admin, Accounting,Finance"
Margin="10,5,10,5" />
凡WEBUSER任何身份驗證的用戶,顯然會計/財務/管理角色有升高的privilages。
我們在頁面上打了幾十個電話,但沒有發現任何問題,但沒有任何問題。可能值得複製/粘貼,看看它是如何。
在情況下,它是值得的,這裏是我們的驗證庫中的可見性屬性:
#region Visibility
public static string GetVisibility(UIElement obj)
{
return (string)obj.GetValue(VisibilityProperty);
}
public static void SetVisibility(UIElement obj, string value)
{
obj.SetValue(VisibilityProperty, value);
}
/// Using a DependencyProperty as the backing store for requiresRole. This enables animation, styling, binding, etc...
public static readonly DependencyProperty VisibilityProperty = DependencyProperty.RegisterAttached(
"Visibility",
typeof(string),
typeof(Authorization),
new PropertyMetadata(Visibility_Callback));
// This callback will be invoked when some control will receive a value for your 'Visibility' property
private static void Visibility_Callback(DependencyObject source, DependencyPropertyChangedEventArgs e)
{
var uiElement = (UIElement)source;
if (App.IsAuthenticated)
{
RecalculateControlVisibility(uiElement);
}
else
{
EventHandler eh = null;
eh = delegate
{
RecalculateControlVisibility(uiElement);
};
App.Authenticated += eh;
RecalculateControlVisibility(uiElement);
}
}
private static void RecalculateControlVisibility(UIElement control)
{
//Authorization.UserHasRole() - is your code to check roles
if (Authorization.UserHasRole(GetVisibility(control)))
{
control.Visibility = Visibility.Visible;
}
else
{
control.Visibility = Visibility.Collapsed;
}
}
#endregion
感謝斯科特,這是沿着我在想什麼線。感謝您驗證我的方法。 – rlcrews 2011-05-04 12:42:00