Sergey K
Sergey K

Reputation: 4114

How correctly get resources from resource dictionary in WPF application?

everyone, in WPF application I have the resource dictionary where is defined a lot of DataTemplates for controls and styles. For example

    <DataTemplate x:Key="PriceColumnCellTemplate">
    <Grid VerticalAlignment="Center">
        <Grid.ColumnDefinitions>
            <ColumnDefinition />
        </Grid.ColumnDefinitions>
        <TextBlock
            Text="{Binding Path=PriceQuotation, Mode=OneWay}"
            Grid.Column="1"
            VerticalAlignment="Center"
            Margin="2,0"
        />
    </Grid>
</DataTemplate>

in code behind class for View I have to get this data template. Now this is implementing in the following way

    private DataTemplate _priceColumnCellTemplate;
    private DataTemplate PriceColumnCellTemplate
    {
        get
        {
            if (_priceColumnCellTemplate == null)
                _priceColumnCellTemplate = (DataTemplate)_applicationResources["PriceColumnCellTemplate"];

            return _priceColumnCellTemplate;
        }
    }

    private DataTemplate _priceColumnCellEditingTemplate;
    private DataTemplate PriceColumnCellEditingTemplate
    {
        get
        {
            if (_priceColumnCellEditingTemplate == null)
                _priceColumnCellEditingTemplate = (DataTemplate)_applicationResources["PriceColumnCellEditingTemplate"];

            return _priceColumnCellEditingTemplate;
        }
    }

    private DataTemplate _alternativePriceColumnCellTemplate;
    private DataTemplate AlternativePriceColumnCellTemplate
    {
        get
        {
            if (_alternativePriceColumnCellTemplate == null)
                _alternativePriceColumnCellTemplate = (DataTemplate)_applicationResources["AlternativePriceColumnCellTemplate"];

            return _alternativePriceColumnCellTemplate;
        }
    }

for each DataTemplate is created private field and the property for get value of this field. In the same way is implementing for Styles.

The problem in this code is when I need to add a new DataTemplate I should add code like above for getting this DataTemplate form resources.

How to do refactor this code to avoid this duplication of code, and save the same functionality, may exist more flexible way to get resources from xaml file.

Please, help me with suggestion or give me an example how to solve this problem. Thanks in advance!

Upvotes: 2

Views: 2703

Answers (1)

Vinit Sankhe
Vinit Sankhe

Reputation: 19895

DataTemplates or any resources need not be held in the code behind view models. They can be dynamically supplied in case of DataTemplateSelectors which dynamically select the data template of any element to whome they apply ...

does this solve your issue better?

Upvotes: 1

Related Questions