将枚举值绑定到3状态复选框

时间:2012-01-11 16:53:14

标签: .net wpf

我有以下枚举

Enum NodeStatusTypes
    Undefined
    Grant
    Deny
End Enum

我试图将一个类绑定到一个列表框,以便该类的每个实例都获得 列表框中的名称权限条目绑定到文本框和3状态复选框。下面的代码部分工作,因为如果我添加一个权限属性为 Grant 的类对象,则会选中该复选框。但是,我还需要取消选中权限 拒绝的对象以及复选框处于“空”状态(例如IsChecked =“null”)的复选框权限未定义。我几乎可以肯定问题在于ConverterParameter,但我无法弄清楚如何处理这个问题。

<ListBox>
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <StackPanel.Resources>
                    <l:EnumToTriStateConverter x:Key="TriConverter" />
                </StackPanel.Resources>
                <CheckBox IsThreeState="True" IsChecked="{Binding Path=Permission, Converter={StaticResource TriConverter}, ConverterParameter={x:Static l:NodeStatusTypes.Grant}}"  />
                <TextBlock Text="{Binding Path=Name}" />
                <TextBlock Text="{Binding Path=Permission}" />
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

以下是每个请求的转换器类:

Public Class EnumToTriStateConverter
    Implements IValueConverter

    Public Function Convert(value As Object, targetType As System.Type, parameter As Object, culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.Convert
        Return value.Equals(parameter)
    End Function

    Public Function ConvertBack(value As Object, targetType As System.Type, parameter As Object, culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.ConvertBack
        Dim retVal As NodeStatusTypes = Nothing
        Select Case value
            Case Nothing
                retVal = NodeStatusTypes.Undefined
            Case True
                retVal = NodeStatusTypes.Grant
            Case False
                retVal = NodeStatusTypes.Deny
        End Select
        Return retVal
    End Function

End Class

1 个答案:

答案 0 :(得分:1)

正确的实现看起来像这样:

Public Function Convert(value As Object, targetType As System.Type,
                        parameter As Object,
                        culture As System.Globalization.CultureInfo) As Object
Implements System.Windows.Data.IValueConverter.Convert

    Dim retVal As Object = Nothing;
    Select Case value
        Case NodeStatusTypes.Undefined
            retVal = Nothing
        Case NodeStatusTypes.Grant
            retVal = True
        Case NodeStatusTypes.Deny
            retVal = False
    End Select

    Return retVal

End Function

转换器参数似乎没有多大意义,您可以从绑定中删除它。