[英]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為零的文件集合中添加任何占位符文件。)
首先,說明為什么這種方法無法立即使用:
SelectedValue
返回一個null
當值SelectedItem
也是null
。 您的ParentFileId
屬性是一個不支持null
值的整數(我想),並且它無法知道您希望如何從null
轉換為整數值。 因此,綁定將引發錯誤,並且該值在您的數據中保持不變。
您需要指定一個簡單的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"/>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.