假设我们有一个DataSource绑定到Database的集合。当然没有空项。如何将 void项添加到ComboBox 中,以便在第一次加载用户时会看到一个空字符串。我不想在Collection中添加一个dummy / void对象。 最佳XAML 。有什么建议吗?
答案 0 :(得分:42)
<ComboBox Name="myComboBox" Width="200" Background="White">
<ComboBox.ItemsSource>
<CompositeCollection>
<ComboBoxItem IsEnabled="False" Foreground="Black">Select Item</ComboBoxItem>
<CollectionContainer Collection="{Binding Source={StaticResource DataKey}}" />
</CompositeCollection>
</ComboBox.ItemsSource>
</ComboBox>
修改强>
在评论中提及@surfen时,BindingProxy是绑定问题的解决方法
答案 1 :(得分:2)
<UserControl.Resources>
<CollectionViewSource x:Key="Modules" Source="{Binding Path=Modules}" />
</UserControl.Resources>
<abv:ComboBox SelectedIndex="0" IsNullable="True"
SelectedItem="{Binding Path=SelectedModule, Mode=TwoWay}">
<abv:ComboBox.ItemsSource>
<CompositeCollection>
<ComboBoxItem Content="{DynamicResource EmptyModuleComboBox}"/>
<CollectionContainer Collection="{Binding Source={StaticResource Modules}}" />
</CompositeCollection>
</abv:ComboBox.ItemsSource>
</abv:ComboBox>
public class ComboBox : System.Windows.Controls.ComboBox
{
public static readonly DependencyProperty IsNullableProperty =
DependencyProperty.Register("IsNullable", typeof(bool), typeof(ComboBox));
public bool IsNullable
{
get { return (bool)GetValue(IsNullableProperty); }
set { SetValue(IsNullableProperty, value); }
}
public ComboBox()
{
Loaded += ComboBox_Loaded;
}
void ComboBox_Loaded(object sender, RoutedEventArgs e)
{
if (IsNullable)
{
this.ItemContainerStyle = new Style();
this.ItemContainerStyle.Setters.Add(new EventSetter()
{
Event = ComboBoxItem.PreviewMouseUpEvent,
Handler = new MouseButtonEventHandler(cmbItem_PreviewMouseUp)
});
}
}
public void cmbItem_PreviewMouseUp(object sender, MouseButtonEventArgs e)
{
if (Items.IndexOf(sender as ComboBoxItem) == 0)
{
SelectedItem = null;
}
}
}
答案 2 :(得分:1)
用于绑定MVVM对象:
strOut = strOut & StrConv(strAlphanumeric, vbNarrow)
对于绑定:
<ComboBox Name="cbbFiltres" SelectedItem="{Binding ElmtInfo, Mode=TwoWay}" Height="26" MinWidth="90" SelectedIndex="0" SelectedValuePath="Id">
<ComboBox.Resources>
<CollectionViewSource x:Key="cvsFiltres" Source="{Binding Elmts.items}"/>
</ComboBox.Resources>
<ComboBox.ItemsSource>
<CompositeCollection>
<model:tblFiltreChamps Desc="{x:Static resx:resMain.enumAucun}" Id="0"/>
<CollectionContainer Collection="{Binding Source={StaticResource cvsFiltres}}" />
</CompositeCollection>
</ComboBox.ItemsSource>
</ComboBox>
通用转换器:
<Label Visibility="{Binding Path=SelectedValue, ElementName=cbbFiltres, Converter={StaticResource NullToVisibility}}" />
在组合框中声明SelectedValuePath非常重要。 : - )
答案 3 :(得分:0)