Question

I'm trying to implement a ConnectionString dialog, where the user can enter all the values which are necessary to create a valid ConnectionString, e.g. UserID, IntegratedSecurity, etc....

There is also a ComboBox which enlists all the available databases which can be found at this endpoint. This ComboBox should only bind to the ItemsSource, when it is opened and not when the user changes for example the UserID.

Is there a easy way to refresh the ItemsSource values only when the Values are displayed(for example when opening the combobox). The Problem is when the user enters invalid values there is always an exception because the user has not finished entering all the necessary values.

I have already tried to implement this with the event ComboBox_DropDownOpened but I wonder if there is a more practical way to achieve this. I have noticed there is a BindingProperty "UpdateSourceTrigger" but I don't know if I can use it for my problem.

Thanks for any help!

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

Solution

If the event ComboBox_DropDownOpened is working you can wrap it in a behavior which should look like this :

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); };
    }
}

To activate the behavior use the two provided attached properties in your XAML :

        <ComboBox a:ItemsSourceBindingOnOpenBehavior.Source="{Binding ViewModelCollection}"/>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top