How to write a method for setting property values in a foreach loop (Silverlight and MVVM related)
I have a Silverlight 4 MVVM app that uses databinding to boolean properties like isEditingCustormer, isEditingOrder, isEditingOrderItem, isEditingEmployee etc. on the ViewModel to set state of certain parts of the View. The requirement is that only one region should be editable, not two at the same time. Therefore inside the ViewModel (when responding to user events) we find oursleves writing code like: isEditingCustomer=false; isEditingOrder=false; isEditingOrderItem=false; ... isEditingEmployee=true;
We would like to have this code in a method, so that we could just call the method and pass it as a parameter the name of the property that should be set to true and all the others should be automatically set to false by that method. Unfortunatelly I don't know开发者_如何学C how to go about doing this. Any help is greatly appreaciated. Thanks. Trex
Personally, I'd be tempted to do something like:
public enum EditMode {
Customer, Order, OrderItem, Employee
}
And actually then you probabaly don't need those bools:
public EditMode EditMode {get;set;}
Or you could replace with properties:
private EditMode editMode;
public bool IsEditingCustomer { get {return editMode == EditMode.Customer;}}
public bool IsEditingOrder { get {return editMode == EditMode.Order;}}
public bool IsEditingOrderItem { get {return editMode == EditMode.OrderItem;}}
public bool IsEditingEmployee { get {return editMode == EditMode.Employee;}}
If you need the bools, perhaps:
public void SomeMethod(..., EditMode mode) {
isEditingCustomer = isEditingOrder =
isEditingOrderItem = isEditingEmployee = false;
switch(mode) {
case EditMode.Customer: isEditingCustomer = true; break;
case EditMode.Order: isEditingOrder = true; break;
case EditMode.OrderItem: isEditingOrderItem = true; break;
case EditMode.Employee: isEditingEmployee = true; break;
default: throw new ArgumentOutOfRangeException("mode");
}
}
精彩评论