create multiple copies of staticresource

落爺英雄遲暮 提交于 2019-12-10 13:58:25

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!