【问题标题】:Binding combobox ItemsSource only when opening仅在打开时绑定组合框 ItemsSource
【发布时间】:2013-07-02 06:30:38
【问题描述】:

我正在尝试实现一个 ConnectionString 对话框,用户可以在其中输入创建有效 ConnectionString 所需的所有值,例如UserID、IntegratedSecurity 等......

还有一个 ComboBox 列出了可以在此端点找到的所有可用数据库。此 ComboBox 应仅在打开时绑定到 ItemsSource,而不应在用户更改(例如 UserID)时绑定。

是否有一种简单的方法可以仅在显示值时(例如打开组合框时)刷新 ItemsSource 值。问题是当用户输入无效值时总是会出现异常,因为用户还没有完成所有必要值的输入。

我已经尝试使用 ComboBox_DropDownOpened 事件来实现这一点,但我想知道是否有更实用的方法来实现这一点。我注意到有一个 BindingProperty“UpdateSourceTrigger”,但我不知道我是否可以用它来解决我的问题。

感谢您的帮助!

<ComboBox Text="{Binding InitialCatalog}"
 SelectedValue="{Binding InitialCatalog}" 
ItemsSource="{Binding Databases}" IsEditable="True"/>

【问题讨论】:

    标签: wpf binding combobox refresh late-binding


    【解决方案1】:

    如果事件ComboBox_DropDownOpened 正在运行,您可以将其包装成如下所示的行为:

    internal class ItemsSourceBindingOnOpenBehavior
    {
        public static readonly DependencyProperty SourceProperty =
            DependencyProperty.RegisterAttached("Source", typeof(ObservableCollection<string>),
                                                typeof(ItemsSourceBindingOnOpenBehavior),
                                                new UIPropertyMetadata(null, OnSourceChanged));
    
        public static ObservableCollection<string> GetSource(DependencyObject obj)
        {
            return (ObservableCollection<string>)obj.GetValue(SourceProperty);
        }
    
        public static void SetSource(DependencyObject obj, ObservableCollection<string> value)
        {
            obj.SetValue(SourceProperty, value);
        }
    
        private static void OnSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            SetSource(d);
        }
    
        private static void SetSource(DependencyObject d)
        {
            var cbo = d as ComboBox;
            if (cbo != null) cbo.DropDownOpened += (s, a) => { cbo.ItemsSource = GetSource(cbo); };
        }
    }
    

    要激活该行为,请使用 XAML 中提供的两个附加属性:

            <ComboBox a:ItemsSourceBindingOnOpenBehavior.Source="{Binding ViewModelCollection}"/>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-02-25
      • 1970-01-01
      • 2013-12-19
      • 1970-01-01
      • 1970-01-01
      • 2014-02-15
      • 1970-01-01
      相关资源
      最近更新 更多