WPF-在不可见的组合框上强制绑定

时间:2019-03-26 18:08:14

标签: c# wpf

我有一个WPF窗口,其中包含多个用户控件,其中一些是不可见的(可见性=隐藏)。这些控件之一具有一个具有ItemsSource绑定的ComboBox,我想在加载窗口/控件时预设其选定的项目。

但是,似乎直到组合框可见时才应用绑定。当我去设置SelectedItem属性并在调试器中遇到一个断点时,我注意到那时ItemsSource为null。有没有办法强迫WPF应用数据绑定并在组合框保持不可见的情况下填充组合框?

可复制的示例:

MainWindow.xaml

<Window x:Class="HiddenComboBoxBinding.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:HiddenComboBoxBinding"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Border x:Name="comboboxParent" Visibility="Collapsed">
            <ComboBox x:Name="cmbSearchType" SelectedIndex="0" ItemsSource="{Binding SearchTypeOptions}" DisplayMemberPath="Name" SelectionChanged="cmbSearchType_SelectionChanged" />
        </Border>
    </Grid>
</Window>

MainWindow.xaml.cs

using System.Linq;
using System.Windows;
using System.Windows.Controls;

namespace HiddenComboBoxBinding
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private ViewModel viewModel { get; set; } = new ViewModel();

        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = viewModel;

            // Add some or all of our search types - in the real code, there's some business logic here
            foreach (var searchType in SearchType.AllSearchTypes)
            {
                viewModel.SearchTypeOptions.Add(searchType);
            }

            // Pre-select the last option, which should be "Bar"
            cmbSearchType.SelectedItem = SearchType.AllSearchTypes.Last();
        }

        private void cmbSearchType_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }
    }
}

ViewModel.cs

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HiddenComboBoxBinding
{
    public class ViewModel : INotifyPropertyChanged
    {
        public ObservableCollection<SearchType> SearchTypeOptions { get; set; } = new ObservableCollection<SearchType>();

        #region INotifyPropertyChanged Members
        private void NotifyPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); }
        public event PropertyChangedEventHandler PropertyChanged;
        #endregion
    }

    public class SearchType
    {
        // Source list of Search Types
        private static List<SearchType> _AllSearchTypes;
        public static List<SearchType> AllSearchTypes
        {
            get
            {
                if(_AllSearchTypes == null)
                {
                    _AllSearchTypes = new List<SearchType>();
                    _AllSearchTypes.Add(new SearchType() { Name = "Foo" });
                    _AllSearchTypes.Add(new SearchType() { Name = "Bar" });
                }
                return _AllSearchTypes;
            }
        }

        // Instance properties - for the purposes of a minimal, complete, verifiable example, just one property
        public string Name { get; set; }
    }
}

1 个答案:

答案 0 :(得分:0)

我能够找出问题所在。设置SelectedItem实际上确实有效(即使那时ItemsSource为null),但是在XAML中,ComboBox的SelectedIndex =“ 0”优先于在后面的代码中设置的SelectedItem。