c# - 当 SelectedValue 为 0 时 WPF 组合框,则组合框不应选择

标签 c# wpf mvvm combobox selectedvalue

我在实现了 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"/>

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

但实际上我得到了已选文件 作为 ComboBox 中的 SelectedItem。

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

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

最佳答案

首先,解释为什么这不能开箱即用:
SelectedValue正在返回 null SelectedItem 时的值也是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;
    }
}

将其作为资源添加到您的 View 中:
<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"/>

关于c# - 当 SelectedValue 为 0 时 WPF 组合框,则组合框不应选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30864046/

相关文章:

C# - 接口(interface) - 帮助接口(interface)的力量

c# - 在 WPF RadChart 中禁用点标记和项目标签

c# - 在具有多次运行的 WPF Textblock 中,如何将样式应用于特定的样式?

c# - 更新属性和乒乓球事件

c# - 有没有一种方法可以将 4 个控件分组到一个 UserControl 或模板中,并在父 UserControl 中使用它并将它们与 MVVM 绑定(bind)?

c# - WP7 中带有图像的消息框

extjs - 从 store 监听器获取 ViewModel

c# - 编辑 View 时,Microsoft Visual Studio XAML UI设计器FileNotFoundException

C# Try-catch 不捕获异常

c# - 如何在初始化期间访问 UserControl 的 XAML 设置属性?