Claw
Claw

Reputation: 474

The ValueConverter in ResourceDictionary is the Singleton?

If I add a ValueConverter which is defined in a .cs file into the ResourceDictionary,and use it as a static resource for many times,Will it create new instances or just use the same one?

---------------------------------ValueConverterDefinition-------------------------------

internal class DateTimeConverter : IValueConverter
{
    #region IValueConverter Members

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        var date = (DateTime)value;
        return date.Day;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }

    #endregion
}

---------------------------------ResourceDictionary-------------------------------

<converter:DateTimeConverter x:Key="DateTimeConverter"></converter:DateTimeToSpecificFormatConverter>
<Style x:Key="ToolTipStyle" TargetType="{x:Type ToolTip}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="ToolTip">
                <Border>
                    <Grid>                           
                        <TextBlock Foreground="Black">
                        <TextBlock.Text>
                            <Binding Path="StartDate" Converter="{StaticResource DateTimeConverter}"></Binding>
                        </TextBlock.Text>
                        </TextBlock>
                        <TextBlock Foreground="Black">
                        <TextBlock.Text>
                            <Binding Path="EndDate" Converter="{StaticResource DateTimeConverter}"></Binding>
                        </TextBlock.Text>
                        </TextBlock>
                    </Grid>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

Upvotes: 0

Views: 881

Answers (1)

brunnerh
brunnerh

Reputation: 185072

It's the same instance, adding it is conceptually equivalent to doing this:

var converter = new DateTimeConverter();
control.Resources.Add("Key", converter);

StaticResource then just looks up that instance via the key.

You can however use x:Shared to change that behavior so that every reference creates a new instance.

Upvotes: 1

Related Questions