问题
I have a template for items control shown below. I need separate instances of colorProvider for each item in the template. Each item in the items control requires a seperate instance of the Color Provider depending on the item it is bound to. How do i create multiple copies of staticresource so that the staticresource is only available for that item.
<ItemsControl x:Name="itemsControl" ItemsSource="{Binding DataList}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Vertical"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid MinHeight="250">
<ContentPresenter Content="{Binding }" ContentTemplateSelector="{StaticResource chartSelector}">
<ContentPresenter.Resources>
<v:ColorProvider x:Key="colorProvider"/>
</ContentPresenter.Resources>
</ContentPresenter>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
回答1:
To return a new instance of a static resource each time it's requested, you can use the x:Shared
attribute. This is documented on MSDN. From my experience with this attribute, you will not get Intellisense support when trying to set it. In your case, the attribute would need to be set on the ColorProvider
in your Resources section, as follows.
<ContentPresenter Content="{Binding }" ContentTemplateSelector="{StaticResource chartSelector}">
<ContentPresenter.Resources>
<v:ColorProvider x:Key="colorProvider" x:Shared=false />
</ContentPresenter.Resources>
</ContentPresenter>
回答2:
If resource value varies on data, you should use Binding in conjunction with value converter that will return the Color.
来源:https://stackoverflow.com/questions/35510867/create-multiple-copies-of-staticresource