2

I'm building a WPF application, using MVVM pattern. I have two bars (rectangles) that should change their length according to the ratio between two numbers. For example, if I decide of total length of 100, and one number is 2 and the other is 3, I would like the first bar to be of length 40, and the second one of length 60.

I have these numbers saved as properties in my ViewModel, but my question is what should the bars width attribute be bound to. I could just add two more properties to the ViewModel one for each bar width, but it doesn't feel right, because this is specific for the view.

Any suggestions?

Thanks,

Gal

Gal Malka
  • 307
  • 3
  • 12

1 Answers1

2

View-specific properties should be kept in the view. The idea of MVVM (or any MV* pattern) is to separate the view from the business logic. A common misunderstanding is to think you can't have any logic or properties in the view. Whilst you should minimise them, purely view-specific properties should live in the view.

Imagine you want to use the view model with a different view, say one aimed at a mobile device. The max width of the bars may be different, but your view model shouldn't care about that.

Hope that helps

Avrohom Yisroel
  • 8,555
  • 8
  • 50
  • 106
  • Thanks, it makes sense. I'm still not sure how to do so, I get the number from the ViewModel, but then I have to process it in the View itself to calculate the width. Do you know how it should be done (where the data binding goes)? – Gal Malka Aug 11 '17 at 20:21
  • @GalMalka Hmm, I think you might be going at this the wrong way. One of the strengths of XAML is the ease with which you can create fluid layouts, where you don't need to worry about control widths. You lay out the controls on a WPF Grid container, and it works out how much space to allocate each control, based on the window size. If your view model property were a percentage, then you could use a value converter to set the width of your rectangle. See this answer for more details https://stackoverflow.com/questions/717299/wpf-setting-the-width-and-height-as-a-percentage-value/717358#717358 – Avrohom Yisroel Aug 13 '17 at 21:07