Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combobox assign null if value does not exist in itemsource

I have a Datagrid, and upon double clicking the selected row, an edit screen is launched. On this edit screen, there are combobox, whose value is binded to the selected row in the grid. Sometimes, the value assigned to the combobox does not exist in the combobox itemSource, so the display on the combobox is empty, but the value is not null. How can I update the value of the selected item, to be null if the value does not exist in the itemsource collection.

In the above scenario, Since, the second screen is bound to the Selected item on the first sreen, the SelectedValue for City is "Los Angeles" and the Display is Empty. But since "Los Angeles" does not exist in the collection, SelectedValue should be null.

like image 288
xaria Avatar asked Nov 13 '22 06:11

xaria


1 Answers

A solution is to set the ItemsSource of the combobox to the list (example: "DeviceNameList") and set the SelectedItem of this combobox to a variable that matches the type of elements inside your list (SelectedDeviceName).

Now when you load your edit screen, it will have bound the list to the combobox and display the variable you set.

You have to write some code to check if the selected item occurs in the list and if not you can set the value to zero.

Example:

XAML code:

<ComboBox ItemsSource="{Binding Path=DeviceNameList}" SelectedItem="{Binding Path=SelectedDeviceName}" />

Code to set the selectedItem:

    /// <summary>
    /// Gets or sets SelectedDeviceName.
    /// </summary>
    public ObservableCollection<string> DeviceNameList
    {
         get
        {
           return mDeviceNameList;
        }

        set
        {
            mDeviceNameList = value;
        }
    }

    /// <summary>
    /// Gets or sets SelectedDeviceName.
    /// </summary>
    public string SelectedDeviceName
    {
        get
        {
            return mSelectedDeviceName;
        }

        set
        {
            mSelectedDeviceName = value;
            NotifyPropertyChanged("SelectedDeviceName");
        }
    }

    /// <summary>
    /// Event PropertyChanged
    /// </summary>
    public event PropertyChangedEventHandler PropertyChanged;


        /// <summary>
    /// Function NotifyPropertyChanged
    /// </summary>
    /// <param name="property">
    /// The property.
    /// </param>
    private void NotifyPropertyChanged(string property)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(property));
        }
    }
like image 93
Enrico Avatar answered Nov 14 '22 22:11

Enrico