自定义标记扩展默认值?

时间:2016-03-25 14:23:28

标签: c# wpf

我创建了一个自定义标记扩展,根据其使用的属性返回布尔值或可见性。

它将作为参数提供的级别与当前用户级别进行比较

现在,当我使用它时系统正在运行:

<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;
    }
}

1 个答案:

答案 0 :(得分:0)

  

但IntelliSense告诉我有两个错误

我假设您使用视觉设计师。

解决方案:不要使用视觉设计师。

两个选项:

  1. 禁用它:工具→选项→XAML设计器→取消选中&#34;启用XAML Designer&#34;
  2. 更改编辑器:右键单击XAML文件→类似于&#34;打开&#34; →选择&#34;源代码编辑器&#34; →设为默认