代码之家  ›  专栏  ›  技术社区  ›  MattE

设置wpf中绑定到组合框的collectionviewsource上的筛选器将自动选择第一个项

  •  0
  • MattE  · 技术社区  · 6 年前

    我解决了无法使用collectionviewsource和icollectionview根据各种条件筛选组合框的问题,但现在我遇到了另一个问题。

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

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

    即使我设置了它绑定到的属性rolestr(公共可访问属性,技术上说rolestr是它使用的私有属性)返回“”时,组合框也会从filteredview显示的第一个项目开始。

    Combobox still shows a value in it, when I simply want it to show up as blank.

    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"/>
    

    ViewModel:

    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属性设置为空,这解决了问题。

    1 回复  |  直到 6 年前
        1
  •  0
  •   l33t    6 年前

    去除 SelectedItem . 添加 IsSynchronizedWithCurrentItem="True" .

    ICollectionView 在内部处理当前项。您可以通过 ICollectionView.CurrentItem 财产。

    推荐文章