WPF являются связанными свойствами в ViewModel нарушение лучших практик MVVM?

Вот случай в качестве примера для разработки:

Я динамично создаю простую Гистограмму с помощью ItemsControl, по моему мнению, и связывая объекты с набором BarViewModels (каждый содержащий процент значение) в моем BarGraphViewModel. Каждая панель должна иметь различный цвет. Цвета должны быть выбраны из набора, например. {Color1, Color2, ..}

Сам набор является постоянным, но количество панелей будет зависеть от обстоятельств.

Простое решение состояло бы в том, чтобы создать простой BarViewModel как так:

public class BarViewModel
{
    public int Percentage { get; set; }

    public SolidColorBrush Stroke { get; private set; }

    public BarGraphViewModel(SolidColorBrush stroke)
    {
        Stroke = stroke;
    }
}

(Я не учел измененное свойство и реализация проверки для краткости),

Теперь я мог просто создать BarViewModels из своего BarGraphViewModel для каждого процента и передать в соответствующем ColorBrush, созданном из моего Цветного набора.

Тогда в Xaml я создал бы простой ItemsTemplate, который свяжет с этими свойствами.

Только теперь, так как это содержит свойство типа SolidColorBrush, мой ViewModel зависит от платформы Представления и если я хочу использовать его в другой среде, это должно будет быть изменено.

Делает это поэтому повреждает лучшие практики MVVM, или это приемлемый (необходимо разграничить где-нибудь, или вещи являются слишком сложными),

Я просто хотел видеть то, что другие люди думают об этом и если существуют другие решения, которые сохраняют ViewModel полностью незнакомым с Уровнем представления без того, чтобы быть слишком сложным. Я мог предположить, что ValueConverters мог помочь?

9
задан Thorsten Lorenz 13 December 2009 в 14:09
поделиться

2 ответа

I see no technical reasons why your VM above is bad, but would personally use a Brush rather than a specific subclass. I don't believe this breaks MVVM best practices because your VM is a model of your view. It does not necessarily have to be agnostic of the technology on which your view is built.

However, there are other reasons why it might be a bad idea. Will your view model likely be used in a non-WPF environment? If so, you'll want an abstraction that can then be translated to a platform-specific construct, with WPF's Brush being one such example. And converters aren't necessarily required for this. Your abstraction can itself be a view model, which then has platform-specific subclasses. For example, you might have a Color view model, and a WpfColor view model inheriting from that.

Do you have designers on your team? If so, the use of a Brush in your VM may inhibit their ability to customize the UI. Your specific case above may be an outlier, but generally speaking, designer and developer collaboration benefits from having the VM expose state, and the view rendering that state. As soon as the VM dictates the visual appearance in any capacity, you've limited the decisions your designers can make.

In my experience, the second reason is a far more common one not to include UI-specific constructs in your VM.

1
ответ дан 4 December 2019 в 12:18
поделиться

Theoretically, the situation you described is against best practice in MVVM. But there is a simple solution to clean your view model up. You should create your own type for representing the color in view model - it can be string, int or enum. Then you can write custom ValueConverter (implementing IValueConverter) to convert view model color type into presentation framework dependent color representation. Converter should be used together with bounding expression. Example on converting bound values is here .

8
ответ дан 4 December 2019 в 12:18
поделиться
Другие вопросы по тегам:

Похожие вопросы: