您能否不仅在 ViewModel 上拥有 IsAdmin 属性,并使用 将仅管理员项目的可见性绑定到该属性BooleanToVisibilityConverter
?
视图模型
public bool IsAdmin
{
get
{
//What ever you do to work out if user is admin
//omitted any INotifyPropertyChanged gubbins
}
}
Xaml
<StackPanel Visibility="{Binding IsAdmin,Converter={StaticResource BooleanToVisibiltyConverter}}"></StackPanel>
转换器
public sealed class BooleanToVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var flag = false;
if (value is bool)
{
flag = (bool)value;
}
else if (value is bool?)
{
var nullable = (bool?)value;
flag = nullable.GetValueOrDefault();
}
if (parameter != null)
{
if (bool.Parse((string)parameter))
{
flag = !flag;
}
}
return flag ? Visibility.Visible : Visibility.Collapsed;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
var back = ((value is Visibility) && (((Visibility)value) == Visibility.Visible));
if (parameter != null)
{
if ((bool)parameter)
{
back = !back;
}
}
return back;
}
}