开发者

Can I have a ValueConverter in my ViewModel?

开发者 https://www.devze.com 2023-01-08 06:55 出处:网络
I have a combo开发者_开发技巧box bound to a collection, so the user can select one of the items.So far, so good.

I have a combo开发者_开发技巧box bound to a collection, so the user can select one of the items. So far, so good.

The content of the combo box is driven by the item, but also by a value in my viewmodel. Imagine the value in my viewmodel is the language, I have dictionary of descriptions by language in my bound item, and I want to display the correct one.

How should I go about this?


This is a classic example of why the ViewModel exists - you want to have logic which depends on trivial state in the view, as well as the main model.

Imagine you are writing a unit test to run against the ViewModel for this behaviour. You would need the ViewModel to have a property mapped to the selected item. The ViewModel would also have another property which varies according to this selected item as well as the other value in the ViewModel you mentioned.

I think of this as the test-driven approach to ViewModel design - if you can't write a unit test to evaluate it then you haven't got the mix of state and published interfaces right.

So, yes, the ViewModel can solve the problem and if you push all the state down into it you can do the unification within the ViewModel.


Make an observable collection in your viewmodel of type Item. Bind the itemsource of your viewmodel to this observable collection.

public class Item
{
public String description {get;set;}
public String language {get;set;}
public override ToString()
{
      return description;
}
}

Selected item would also be bound to a property of type Item as well.

The override of ToString displays the description.

The Selected item propery will have a reference to the selected object property where you can get the language from.

0

精彩评论

暂无评论...
验证码 换一张
取 消