Sheen
Sheen

Reputation: 3431

What is simplest way to bind this database content to WPF controls?

I am new to WPF.

I have a database table with 2 columns: Category, Type. Primary key combination is (Category, Type). Type is subordinate to Category, meaning 1 Category containing multiple Type.

Now, in my WPF UI, I have 2 comboBox controls. The first bind to distinct category list in the DB table. I have done it by binding the control to a DB view of distinct(Category). The second needs to show Type list belonging to the category currently selected in first control.

I did research but have no idea how to easily do it. I tried creating a stored procedure to select the wanted Type value list based on Category given, but don't know how to pass the selected Category to the stored procedure in XAML. Must I use code rather than XAML to do it? What is your suggestion?

Thanks a lot

Upvotes: 0

Views: 626

Answers (2)

Kevin DiTraglia
Kevin DiTraglia

Reputation: 26058

I would create an object to hold your categories that contain each type possible for that category. Something like...

public class Category
{
    public ObservableCollection<string> Types { get; set; }
}

Then when you initialize every Category, you can set which Types are allowed in...

public class MyClass
{
    public ObservableCollection<Category> Categories { get; set; }
    public MyClass()
    {
         InitializeComponent();
         ObservableCollection MyTypes = new ObservableCollection();
         MyTypes.Add("type1");
         MyTypes.Add("type2");
         MyTypes.Add("Type3");
         Categories.Add(new Category() { Types = MyTypes });
         //Probably a more elegant way to do this, but hard to say based on information given

         this.DataContext = this;
    }
}

Lastly you can bind the first combobox to the category list, and the second to the Types list of the selected item of the other combobox.

<ComboBox Name="cboCategory" ItemsSource = "{Binding Categories}" />

<ComboBox ItemsSource = "{Binding ElementName=cboCategory, Path=SelectedItem.Types}" />

Upvotes: 2

Ravindra Gorana
Ravindra Gorana

Reputation: 1

The thing is that whenever we are showing data of that kind usually we will first fetch the data and then prepare the object what we need and after it bind it wpf control.

Now first you already binded to combobox so on the basis of selecteditem you need to fill the other drop down list and bind it as well on SelectionChanged of first or Category List you can use property change event also.

Note : if the data is huge then we will use CTE or Paging kind of thing to fetch data.

Upvotes: 0

Related Questions