WPF MVVM: конвенция по конфигурации для ResourceDictionary?

Вы можете указать, что приложение реагирует непосредственно в вашей конфигурации при запуске, что-то вроде этого

6
задан Spooky 19 June 2015 в 20:44
поделиться

2 ответа

Вместо того, чтобы писать код для явного добавления объектов в ResourceDictionary, как насчет создания правильного представления по требованию? Вы можете сделать это с помощью ValueConverter.

Ваши ресурсы будут выглядеть следующим образом:

<Views:ConventionOverConfigurationConverter x:Key="MyConverter"/>
<DataTemplate DataType="{x:Type ViewModels:ViewModelBase}">
    <ContentControl Content="{Binding Converter={StaticResource MyConverter}}"/>
</DataTemplate>

Вам все еще нужен ресурс DataTemplate, но пока все ваши ViewModels имеют общий базовый класс, вам понадобится только один DataTemplate для принятия позаботьтесь обо всех.

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

public class ConventionOverConfigurationConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter,
        CultureInfo culture)
    {
        // value is the ViewModel. Based on its GetType(), build a string
        // with the namespace-qualified name of the view class, then:
        return Activator.CreateInstance(Type.GetType(viewName));
    }
    public object ConvertBack(object value, Type targetType,
        object parameter, CultureInfo culture)
    {
        throw new NotSupportedException();
    }
}

Все, что вам нужно сделать, это написать логику внутри Convert, которая будет зависеть от того, находятся ли ваши Views и ViewModels в одном и том же пространстве имен или нет.

17
ответ дан 8 December 2019 в 14:47
поделиться

I decided to do pretty much hthe same thing so I load my DataTemplates directly into the ResourceDictionary using

    private void RegisterResources()
    {
        ResourceDictionary dictionary = new ResourceDictionary();
        dictionary.Source = new Uri("pack://application:,,,/StartupModule;Component/UIResources.xaml");
        Application.Current.Resources.MergedDictionaries.Add(dictionary);
    }

where the UIResources file is a ResourceDictionary xamls file containing all of our DataTemplates

-1
ответ дан 8 December 2019 в 14:47
поделиться
Другие вопросы по тегам:

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