IValueConverter无法正常工作

时间:2014-01-03 19:35:56

标签: wpf binding ivalueconverter

我想为我的系统创建一个用户权限验证,我创建了一个enum class Permission包含所有类型的权限,例如:CanInsert,CanEdit,CanAccess,CanDelete等......

在我的class User中有一个属性列表包含该用户拥有的所有权限

我创建了converter PermissionToVisibleHiddenConverter用于控件的可见性

public class PermissionToVisibleHiddenConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        User loger = (User)value;

        /* Before edit
        if (loger.Permissao.Contains(Permission.Principal_AbrirLoja))
            return Visibility.Collapsed;
        else
            return Visibility.Collapsed; */

        if (loger.Permissao.Contains(Permission.Principal_AbrirLoja))
            return Visibility.Visible;
        else
            return Visibility.Collapsed;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

但是当我尝试使用此代码进行绑定时,它无法正常工作

<!--<MenuItem Header="Abrir loja" Visibility="{Binding Loger, Converter={StaticResource BoolToVisibleHiddenConverter}, ElementName=window, TargetNullValue=Collapsed, Mode=OneWay}"/>-->
<MenuItem Header="Abrir loja" Visibility="{Binding Loger, Converter={StaticResource PermissionToVisibleHiddenConverter }, ElementName=window, TargetNullValue=Collapsed, Mode=OneWay}"/>

这个MenuItem父窗口的窗口与此类似,但Loger不为null

public partial class MainWindow : Window
{
    User Loger { get; set; }

    public MainWindow()
    {
        InitializeComponent();
    }
}

此代码不会抛出任何异常或错误,只是不执行任何操作

问题在哪里?

1 个答案:

答案 0 :(得分:1)

1)您的财产不公开2)您需要通知

public partial class Window1 : Window,INotifyPropertyChanged
{
    public Window1()
    {
        InitializeComponent();
    }

    User loger;

    public User Loger 
    { 
        get{return  loger;}
        set { loger= value; OnPropertyChanged("Loger "); }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged(string propertyName)
    {
        if (this.PropertyChanged != null)
            this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}