【问题标题】:Setting Filter on CollectionViewSource bound to ComboBox in WPF Automatically selects the first item在WPF中绑定到ComboBox的CollectionViewSource上设置过滤器自动选择第一项
【发布时间】:2019-04-02 13:40:00
【问题描述】:

我使用 CollectionViewSource 和 ICollectionView 解决了无法根据各种条件过滤组合框的问题,但现在我遇到了另一个问题。

当我设置这些过滤器时,它会自动选择过滤器中的第一个项目,当我不想选择任何东西时,我只是希望能够选择那里的项目。

有没有办法在不自动选择第一个项目的情况下设置过滤器?

即使我将绑定到的属性 RoleStr(以及公共可访问属性,技术上 _roleStr 是它使用的私有属性)设置回“”,组合框也会从 FilteredView 中的第一项显示开始。

XAML:

<ComboBox  x:Name="empRoleCB" Height="20" Width="175" HorizontalAlignment="Left"   VerticalAlignment="Top" Margin="0,5" IsEnabled="{Binding ElementName=empDeptCB, Path=Text.Length, Mode=OneWay}"   ItemsSource="{Binding Path=MyRoleFilter}" SelectedItem="{Binding RoleStr}" SelectionChanged="empDeptCB_SelectionChanged" Loaded="empRoleCB_Loaded"/>

视图模型:

public partial class EmployeeMenu : Window
{
    EmployeeMenuVM empVM = new EmployeeMenuVM();
    public EmployeeMenu()
    {

        DataContext = empVM;
        empVM.MyRoleFilter = new CollectionViewSource { Source = empVM.Role }.View;

        InitializeComponent();
    }
    private void empRoleCB_Loaded(object sender, RoutedEventArgs e)
    {
        if(loggedUser[0].Role == (int)Roles.SrMgr)
        {
            empVM.MyRoleFilter.Filter = a => { return (string)a == Roles.Mgr.ToString() || (string)a == Roles.TeamLead.ToString() || (string)a == Roles.User.ToString(); };
        }
        else if(loggedUser[0].Role == (int)Roles.Mgr)
        {
            empVM.MyRoleFilter.Filter = a => { return (string)a == Roles.TeamLead.ToString() || (string)a == Roles.User.ToString(); };
        }
       else if (loggedUser[0].Role == (int)Roles.TeamLead)
        {
            empVM.MyRoleFilter.Filter = a => { return  (string)a == Roles.User.ToString(); };
        }

        empVM.RoleStr = "";
    }

查看:

private ObservableCollection<string> _role = new ObservableCollection<string>(Enum.GetNames(typeof(Global.Roles)));
private string _roleStr;
public IEnumerable<string> Role { get => _role; }
public ICollectionView MyRoleFilter { get; set; }
public string RoleStr
{
     get => _roleStr;
     set => SetProperty(ref _roleStr, value);
}

更新已解决:

运行过滤器后,我必须手动将 Combobox.Text 属性设置为空,这解决了问题。

【问题讨论】:

  • 在 SO 上提问时请提供MCVE
  • 我很确定如果您在更改过滤器之前禁用组合框,然后在设置过滤器后重新启用,它不应该进行选择。
  • @AgapwIesu 不,这不是真的,组合框被禁用,但它最终仍然显示一个值。
  • 好的。对不起。从几年前有这个问题的模糊记忆中走出来。在选择中设置一个“请选择一个值”类型的选项怎么样?

标签: c# wpf filter collectionviewsource


【解决方案1】:

删除SelectedItem。添加IsSynchronizedWithCurrentItem="True"

ICollectionView 在内部处理当前项目。可以通过ICollectionView.CurrentItem属性查询。

【讨论】:

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