I have this table:
I use in my project this view Called NewItem and in this view there is two combobox.
I would like to do this : that in the combobox Group there are all DESCRIPTION of table GROUP, and when i choose an item of this description (of first combobox) the second combobox fills of descriptions relating only to that description that I have chosen before.
This is some code:
XAML NewItemView:
<ComboBox Height="21" HorizontalAlignment="Left" Margin="89,99,0,0"
VerticalAlignment="Top" Width="106" x:Name="Group" SelectedItem="{Binding SelectedGroup}" />
The ViewModel code is like:
[Export(typeof(IScreen))]
public class NewItemViewModel : Screen
{
public string SelectedGroup { get; set; }
public String[] Group { get { return Groups; } }
[..]
//Constructor
public NewArticleViewModel()
{
Groups = GetGroups();
}
//Method
private string[] GetGroups()
{
OleDbConnection conn = new OleDbConnection(StringConn);
List<Group> groups = new List<Group>();
conn.Open();
groups = conn.Query<Group>(Q_SELECT_GROUPS,null,null).ToList();
conn.Close();
string[] array = new string[groups.Count];
for (int i = 0; i < array.Length; i++)
{
array[i] = groups[i].Descripion;
}
return array;
}
}
GROUP CLASS IS :
public class Group
{
public int Id { get; set; }
public string Descripion { get; set; }
}
I wanted to specify that i use Caliburn.Micro and Dapper for acces'query.
Thank you so much !
This is a typical Master/Detail scenario and there is a typical and easy way to solve it.
I. Instead of only loading descriptions as a string[]
inside your GetGroups
method, load the enitre Group
object or if there is many properties create a view model with only the two needed properties, something like this:
class GroupViewModel {
public int GroupId {get; set;}
public string Description {get; set;}
}
II. In NewItemViewModel
add a property for the second ComboBox, let's say
class NewItemViewModel {
private ObservableCollection<SubgroupViewModel> _subgroups;
public ObservableCollection<SubgroupViewModel> Subgroups
{
get {
if (_subgroups == null)
_subgroups = new ObservableCollection<SubgroupViewModel>();
return _subgroups;
}
set {
_subgroups = value;
NotifyPropertyChanged("Subgroups");
}
}
}
III. Now in your NewItemViewModel
, the properties become something like this:
class NewItemViewModel {
public GroupViewModel SelectedGroup
{
set {
var currentlySelected = value;
// LOAD ALL RELATED Subgroup Descriptions FOR currentlySelected.GroupId;
Subgroups = // LOADED Subgroup DESCRIPTIONS
}
}
public ObservableCollection<GroupViewModel> Group { get { return Groups; } }
}
I hope you get the idea, this is basic outline of the method. I think you can improve it a bit by leveraging some of Selectors Important Properties and using other techniques for loading the data.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With