WPF Combobox 当 SelectedValue 为 0 时,Combobox 不应 select

WPF Combobox when SelectedValue is 0 then the Combobox should not select

我在实现了 MVVM 的 WPF 应用程序中有一个组合框。看起来,-

<ComboBox x:Name="cboParent" 
              SelectedValuePath="FileId"
                  DisplayMemberPath="FileName"
                  IsEditable="True"
                  ItemsSource="{Binding Files}"
                  MaxDropDownHeight="125"
              SelectedValue="{Binding Path=SelectedFile.ParentFileId}"
               SelectedItem="{Binding Path=SelectedParentFile, Mode=TwoWay}" Height="26"/>

Files 集合有一个自引用密钥 ParentFileId。现在有时这个 ParentFileId 会是零;意味着没有父文件。在那种情况下,我希望虽然下拉列表将包含所有文件,但不会有任何 SelectedItem。

但实际上我得到的是 SelectedFile 作为 ComboBox 中的 SelectedItem。

当 ParentFileId 为零时,我可以在不选择任何内容的情况下获取 ComboBox 吗?

(我不想在 FileId 为零的文件集合中添加任何占位符文件。)

首先,解释为什么这不能开箱即用:

SelectedItem 也是 null 时,

SelectedValue 返回一个 null 值。您的 ParentFileId 属性 是一个不支持 null 值的整数(我猜),它无法知道您希望如何从 null 转换到一个整数值。所以 Binding 抛出一个错误,而你的数据中的值保持不变。

您需要指定如何使用简单的 Converter 转换这些空值,如下所示:

public class NullToZeroConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value.Equals(0))
            return null;
        else
            return value;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value == null)
            return 0;
        else
            return value;
    }
}

将其作为资源添加到您的视图中:

<Grid ...>
    <Grid.Resources>
        <local:NullToZeroConverter x:Key="nullToZeroConverter" />
        ...
    </Grid.Resources>
    ...
</Grid>

然后在您的 SelectedValue 绑定中使用它:

<ComboBox x:Name="cboParent" 
          SelectedValuePath="FileID"
          DisplayMemberPath="FileName"
          IsEditable="True"
          ItemsSource="{Binding Files}"
          MaxDropDownHeight="125"
          Validation.Error="cboParent_Error"
          SelectedValue="{Binding Path=SelectedFile.ParentFileID,
                                  Converter={StaticResource nullToZeroConverter}}"
          SelectedItem="{Binding Path=SelectedParentFile, Mode=TwoWay}"
          Height="26"/>