【问题标题】:Binding an enumeration value to a 3-state checkbox将枚举值绑定到三态复选框
【发布时间】:2012-01-11 16:53:13
【问题描述】:

我有以下枚举

Enum NodeStatusTypes
    Undefined
    Grant
    Deny
End Enum

我正在尝试将一个类绑定到一个列表框,以便该类的每个实例都可以 列表框中的 namepermission 条目绑定到文本框和三态复选框。下面的代码部分工作,如果我添加一个其 permission 属性为 Grant 的类对象,那么复选框将被选中。但是,对于 permissionDeny 的对象以及复选框处于“null”状态(例如 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

【问题讨论】:

  • 能否分享一下转换器代码?

标签: .net wpf


【解决方案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

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

【讨论】:

  • 效果很好。我还对 ConvertBack 进行了更改,这也有效。
  • @WhiskerBiscuit:ConvertBack 需要进行哪些更改?我认为从一开始就是正确的。
猜你喜欢
  • 2023-03-06
  • 2012-08-19
  • 2011-12-06
  • 2018-06-09
  • 2012-04-21
  • 2016-02-06
  • 2012-01-21
  • 2016-03-13
  • 1970-01-01
相关资源
最近更新 更多