【发布时间】:2010-05-25 02:04:21
【问题描述】:
生日快乐!
我希望我的 WPF ComboBox 在其数据绑定选择为 null 时显示一些替代文本。
视图模型具有预期的属性:
public ThingoSelectionViewModel : INotifyPropertyChanged {
public ThingoSelectionViewModel(IProvideThingos) {
this.Thingos = IProvideThingos.GetThingos();
}
public ObservableCollection<Thingo> Thingos { get; set; }
public Thingo SelectedThingo {
get { return this.selectedThingo; }
set { // set this.selectedThingo and raise the property change notification
}
// ...
}
视图以预期的方式将 XAML 绑定到视图模型:
<ComboBox x:Name="ComboboxDrive" SelectedItem="{Binding Path=SelectedThingo}"
IsEditable="false" HorizontalAlignment="Left" MinWidth="100"
IsReadOnly="false" Style="{StaticResource ComboboxStyle}"
Grid.Column="1" Grid.Row="1" Margin="5" SelectedIndex="0">
<ComboBox.ItemsSource>
<CompositeCollection>
<ComboBoxItem IsEnabled="False">Select a thingo</ComboBoxItem>
<CollectionContainer
Collection="{Binding Source={StaticResource Thingos}}" />
</CompositeCollection>
</ComboBox.ItemsSource>
</ComboBox>
楔入顶部的ComboBoxItem 是一种在顶部获得额外物品的方法。它是纯 chrome:视图模型保持纯粹和简单。只有一个问题:只要 ComboBox 的选择为空,用户就希望显示“Select a thingo”。
用户确实不想要默认选择的东西。他们希望看到一条消息,告诉他们选择一个东西。
如果.ActualThingo 属性为空,我想避免使用ThingoWrapper 类和ToString 方法返回“Select a thingo”来污染视图模型,在我填充@ 时包装每个Thingo 987654330@,并想办法阻止用户选择无效的Thingo。
有没有办法使用纯 XAML 或纯 XAML 以及视图的代码隐藏类中的几行代码在 ComboBox' 边界内显示“选择一个东西”?
【问题讨论】:
-
FWIW:我最终实现了 ThingoWrapper,修改了 ThingoSelectionViewModel 以应对包装的空值的选择,并找到自动选择 Whatsy 和 Fadoozamy 对象的方法,因此我不必包装它们,也。