【问题标题】:WPF Combobox when SelectedValue is 0 then the Combobox should not select当 SelectedValue 为 0 时 WPF 组合框,则组合框不应选择
【发布时间】:2015-09-01 01:30:42
【问题描述】:

我在实现了 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 为 0 时,我可以在不选择任何内容的情况下获取 ComboBox 吗?

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

【问题讨论】:

  • 只是一个想法。为什么不将引用设为可空?那么它将为空而不是零。
  • 其实目前的实现方式是这个自引用键不为空。在没有映射的地方,它的值为零。因此,这不是一个选项。

标签: c# wpf mvvm combobox selectedvalue


【解决方案1】:

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

SelectedItem 也是null 时,SelectedValue 返回一个null 值。您的 ParentFileId 属性是一个不支持 null 值的整数(我猜),它无法知道您希望如何从 null 转换为整数值。因此 Binding 会引发错误,并且值在您的数据中保持不变。

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

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"/>

【讨论】:

  • 这就是我要找的!!非常感谢!
猜你喜欢
  • 2021-10-11
  • 2015-07-11
  • 1970-01-01
  • 2021-10-15
  • 1970-01-01
  • 2017-08-20
  • 1970-01-01
  • 2012-07-14
  • 2013-02-23
相关资源
最近更新 更多