【问题标题】:Wpf Comboxbox selectable default itemWpf Combobox 可选默认项
【发布时间】:2011-04-22 14:46:14
【问题描述】:

我有一个组合框,它数据绑定到我的视图模型中的 observablecollection。我可以让我的列表填充数据,但我也想添加一个默认项目,如“--All Models--”。下面的代码将“--All Models--”显示为默认项,但如果您选择其他项,则无法选择。

<ContentControl Content="{Binding Items}">
    <ContentControl.ContentTemplate>
        <DataTemplate>
            <Grid>
                <ComboBox x:Name="cb" ItemsSource="{Binding}"/>
                <TextBlock x:Name="tb" Text="--Choose One--" IsHitTestVisible="False" Visibility="Hidden"/>
            </Grid>
            <DataTemplate.Triggers>
                <Trigger SourceName="cb" Property="SelectedItem" Value="{x:Null}">
                    <Setter TargetName="tb" Property="Visibility" Value="Visible"/>
                </Trigger>
            </DataTemplate.Triggers>
        </DataTemplate>
    </ContentControl.ContentTemplate>
</ContentControl>

我尝试过使用复合集合,但这似乎不起作用。有没有办法做到这一点?

提前致谢!

【问题讨论】:

    标签: wpf xaml combobox


    【解决方案1】:

    CompositeCollection 应该可以工作,如果你知道如何使用它;关于它的一件重要的事情是它继承DataContext,这意味着您需要以其他方式引用您的源,如果该方法是x:Reference,您可能不会创建循环引用,这可以通过将集合放在引用元素的资源中来避免。例如

    <Window.Resources>
        <CompositeCollection x:Key="compCollection">
            <ComboBoxItem Content="-- All Models --"/>
            <CollectionContainer Collection="{Binding MyCollection, Source={x:Reference Window}}"/>
        </CompositeCollection>
        ...
    </Window.Resources>
    

    然后您可以通过ItemsSource="{StaticResource compCollection}" 使用它。

    【讨论】:

    • 这是一个更简洁的答案。从 MVVM 的角度来看,要干净得多。
    【解决方案2】:

    将视图交互逻辑构建到视图模型中。我的建议是让 Observable 集合类型成为由源列表填充的视图模型,再加上一个用于“未选择”项目的视图模型。

    类似

    public class ItemViewModel
    {
         public string Description { get; set; }
         public int Id { get; set; }
    }
    
    public class ViewModel : ViewModelBase
    {        
        public ObservableCollection<ItemViewModel> Items { get; set; } // Bound to ContentControl
    
        private void Init()
        {
            Items = new ObservableCollection<ItemViewModel>();
            Items.Add(new ItemViewModel() { Description = "--choice one--" , Id = null });
            Items.AddRange(Model.Items.Select(i=> new ItemViewModel() { Description = i.Description , Id = i.Id }));
        }
    }
    

    然后你可以用空语义处理 SelectedItem 的 Id。

    【讨论】:

      【解决方案3】:

      您可以将您的集合泛型类型更改为 object 并在那里添加 --All Models-- 东西。

      【讨论】:

        猜你喜欢
        • 2013-05-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-10-10
        • 1970-01-01
        相关资源
        最近更新 更多