我创建了一个自定义标记扩展,根据其使用的属性返回布尔值或可见性。
它将作为参数提供的级别与当前用户级别进行比较
现在,当我使用它时系统正在运行:
<Button Visibility="{u:RestrictTo User}" IsEnabled="{u:RestrictTo Manager}" />
但IntelliSense告诉我有两个错误:
''不是属性'Visibility'的有效值。
''不是属性'IsEnabled'的有效值。
如果这是重要的,这里是我对RestrictTo标记扩展的实现:
public class RestrictTo : MarkupExtension
{
public UserLevel AccessLevel { get; set; }
public RestrictTo() { }
public RestrictTo(object accessLevelStr)
{
AccessLevel = (UserLevel) Enum.Parse(typeof(UserLevel), accessLevelStr.ToString());
}
public override object ProvideValue(IServiceProvider serviceProvider)
{
var valueService = (IProvideValueTarget) serviceProvider.GetService(typeof(IProvideValueTarget));
if (valueService == null)
return null;
var property = valueService.TargetProperty as DependencyProperty;
if (property == null)
return null;
var target = valueService.TargetObject as FrameworkElement;
if (target == null)
return null;
var userManager = Application.Current.Resources["UserManager"] as UserManager;
if (userManager == null)
return null;
var binding = new Binding()
{
Path = new PropertyPath("UserLevel"),
Source = userManager,
Mode = BindingMode.OneWay,
Converter = new UserLevelToAccessConverter() { AccessLevel = this.AccessLevel }
};
return binding.ProvideValue(serviceProvider);
}
}
转换器:
public class UserLevelToAccessConverter : IValueConverter
{
public UserLevel AccessLevel { get; set; }
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
UserLevel userLevel = (UserLevel) Enum.Parse(typeof(UserLevel), value.ToString());
if(targetType == typeof(bool))
return userLevel >= AccessLevel;
if (targetType == typeof (Visibility))
return (userLevel >= AccessLevel) ? Visibility.Visible : Visibility.Collapsed;
throw new ArgumentException("UserLevel can only be converted to a bool or a visibility");
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return null;
}
}
答案 0 :(得分:0)
但IntelliSense告诉我有两个错误
我假设您使用视觉设计师。
解决方案:不要使用视觉设计师。
两个选项: