This seems like a simple task but I am having trouble finding the right keywords that describe my situation. For background I'm using Caliburn.Micro and attempting my first true MVVM implementation so I'm still learning the basics, but this questions isn't really specific to the framework/pattern.
Basically when a form loads, only the first combobox is available, then once a selection is made, the second one becomes available, and so on. When the user changes a previously made selection, the comboboxes that come after the one that changed all clear (as each combobox depends on the selections made previously). The next combobox (after the one that changed) will repopulate after a new query to the database.
I have a method that I believe will work, but it feels kind of clunky and I'm wondering if anyone has suggestions on how to improve or rewrite it. The final form will have approximately 30 comboboxes so I'm trying to find a way to elegantly handle the situation without writing a custom function for each "Selected" setter.
An example of a Combobox variable (named to conform with Caliburn's binding conventions).
public BindableCollection<string> OrderCategorys;
private string selectedOrderCategory;
public string SelectedOrderCategory
{
get { return selectedOrderCategory; }
set
{
selectedOrderCategory = value;
NotifyOfPropertyChange(() => SelectedOrderCategory);
}
}
For this example, imagine there are three similar "Selected" and "BindableCollection" variables with the following base names:
private List<string> propertyNames = new List<string> { "OrderCategory", "OrderSubcategory", "Item" };
The solution I came up with using reflection:
private void OrderViewModel_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
if(propertyName.Contains("Selected"))
{
string propName = e.PropertyName.Replace("Selected", "");
ClearAfter(propName);
GetSelections(propName);
}
}
private void ClearAfter(string propName)
{
for (int i = propertyNames.IndexOf(propName) + 1; i < propertyNames.Count; i++)
{
this.GetType().GetProperty("Selected" + propName).SetValue(this, string.Empty);
this.GetType().GetProperty(propName + "s").SetValue(this, new BindableCollection<string>());
}
}
private void GetSelections(string propName)
{
int index = propertyNames.IndexOf(propName) + 1;
string nextPropName = propertyNames[index];
BindableCollection<string> selections = RunQuery(nextPropName);
this.GetType().GetProperty(propName + "s").SetValue(this, selections);
}
private BindableCollection<string> RunQuery(string propName)
{
// Run query based on propName and return list
}
Thoughts on this approach? Is there a better way of handling this that I'm missing?
Aucun commentaire:
Enregistrer un commentaire