开发者

How to implement WPF ValueConverter that needs data from viewmodel?

i am writing an application that has a viewmodel and a usercontrol that displays data from this viewmodel. The viewmodel contains an entity "Appointment", and those appointments have a property "UserName".

When I display the appointments, I want to use a value-converter to get a color for the user (depending on "UserName"), but the colors are not contained in the entity "Appointment", so I wanted to create a value-converter that uses the entity "User" from the viewmodel.

What is the best way to use another entity from the viewmodel inside the converter?

Is it possible to access the viewmodel from the use开发者_JAVA技巧rcontrol? I tried to place the converter inside my viewmodel-class, but can I access this class from the usercontrol?

I figured out that the following possibilities might work:

  1. Adjust the viewmodel so that each appointment also contains the color. But I don't want to do this because I don't want to mess with the viewmodel.

  2. Set the converter-parameter from the class that also contains the viewmodel at startup. (Does this work?)

  3. Use x:Reference to databind the converter parameter to the viewmodel that is unknown at compile-time.(Is this possible?)


Converter parameter is the way to go.

Why is the viewmodel unknown at compile time? Bindings are not compile time checked anyway.

Is the UserControl.DataContext being set to an instance of Appointment, you should be able to set the parameter to {Binding UserName} or {Binding Appointment.UserName} depending on exactly what you are setting as the DataContext on the UserControl.


I would suggest that you re-examine your reluctance to modify the view model. The purpose of having a view model in the first place is so that everything that the view needs can be found in one place. Coming up with elaborate value converters to prevent modifying the view model is an approach that gets increasingly unmaintainable the more you do it.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜