2013-07-04 70 views
1

我試圖實現一個ConnectionString對話框,其中用戶可以輸入創建一個有效的ConnectionString所需的所有值,例如, UserID,IntegratedSecurity等......Binding combobox ItemsSource only when when

還有一個ComboBox,它列出了可在此端點找到的所有可用數據庫。這個ComboBox應該只綁定到ItemsSource,當它打開時,而不是當用戶改變例如UserID。

只有在顯示值時(例如打開組合框時)纔有刷新ItemsSource值的簡單方法。問題在於,當用戶輸入無效值時,總會有異常,因爲用戶尚未完成輸入所有必要的值。

我已經試圖用事件ComboBox_DropDownOpened來實現這一點,但我想知道是否有更實際的方法來實現這一點。我注意到有一個BindingProperty「UpdateSourceTrigger」,但我不知道我是否可以用它來解決我的問題。

感謝您的幫助!

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

回答

3

如果事件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}"/>