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