SHRI
SHRI

Reputation: 2466

How to show default value in a combobox using binding?

I have the following code behind class,

I have a cobobox in xaml. I want to bind it with this class. The code below make combobox to contain 2 items "Arbitrary" and "Configurable"

But when I run the application, combobox is empty. No default value is selected. How to make this?

public class ReadData:INotifyPropertyChanged
{

    private string typeData="Arbitrary";
    private string[] typeDataList={"Arbitrary", "Configurable"};
    private ICollectionView typeDataList;

    public string[] TypeDataList
    {
        get
        {
            return typeDataList;
        }
        set
        {
            typeDataList=value;
            NotifyProertyChanged("TypeDataList");
        }
    }

public string TypeData
{
get
{
return typeData;
}
set
{
typeData=value;
NotifyPropertyChanged("TypeData");
}

public ICollectionView TypeDataListView
{
get
{
typeDataListView=CollectionViewSource.GetDefaultView(typeDataList);
return typeDataListView;
}
set
{
typeDataListView=value;
//typeDataList= ???
}
}

XAML file

<ComboBox ItemSource={Binding TypeDataListView}" IsSynchronizedWithCurrentItem="True" SelectedItem="{Binding typeData}" Height="23" Width="120"/>

Upvotes: 0

Views: 900

Answers (1)

Bill Zhang
Bill Zhang

Reputation: 1939

I guess you do not want only binding of items source but selection of the combobox is also important to you so you would like to add selection on view model also. There are two ways:

  1. Add a SelectedTypeData property on ReadData class, whose type is string. Bind SelectedItem of ComboBox to SelectedTypeData. Then in the initialization of your ReadData object, you can assign SelectedTypeData a default value as default selection on ComboBox.

  2. Add an TypeDataListView property on ReadData class, whose type is ICollectionView. It might require your TypeDataList is a List. It can be generated by calling CollectionViewSource.GetDefaultView(...). You can assign its CurrentItem property your default selection and assign Combobox's IsSynchronizedWithCurrentItem property to true so you can sync combobox's selecteditem with your TypeDataListView's CurrentItem.

If you do not want to add selection on view model, you can add a Loaded event in code behind and assign combobox's selected item manually in the handler.

Upvotes: 1

Related Questions