如果我将.cs文件中定义的ValueConverter添加到ResourceDictionary中,并将其多次用作静态资源,它会创建新实例还是仅使用相同的实例?
--------------------------------- 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>
答案 0 :(得分:1)
它是同一个实例,添加它在概念上等同于这样做:
var converter = new DateTimeConverter();
control.Resources.Add("Key", converter);
StaticResource
然后只需通过密钥查找该实例。
但是,您可以使用x:Shared
更改该行为,以便每个引用都创建一个新实例。