View 不能被多个 Listview 共享

View can't be shared by more than one Listview

我遇到了很多其他人以前遇到过的问题。我尝试使用一种样式,其中包含由多个控件组成的 GridView。

我在网上搜索了答案,得到了两个解决方案:

我尝试了两种解决方案(甚至同时尝试),但是当我将样式应用到第二个控件时错误仍然出现。

样式是这样的

<Style x:Key="MyCustomStyle" TargetType="{x:Type MyUserControl}" BasedOn="{StaticResource MyUserControlBaseStyle}">
    <Setter Property="Watermark" Value="{x:Static LabelResources.Caption}"/>
    <Setter Property="ErrorText" Value="{Binding Converter={StaticResource FormatStringConverter}, ConverterParameter={x:Static LabelResources.Caption}}"/>
    <Setter Property="LookupTemplate">
        <Setter.Value>
            <DataTemplate DataType="{x:Type LookupResult}">
                <StackPanel Orientation="Horizontal">
                    <TextBlock Text="{Binding Name}" Margin="0,0,2,0"/>
                </StackPanel>
            </DataTemplate>
        </Setter.Value>
    </Setter>

    <Setter Property="SuggestionsView" Value="{DynamicResource CustomGridView}"/>
</Style>

这里是 GridView

<GridView x:Key="CustomGridView" x:Shared="False">
    <GridViewColumn Header="{x:Static resources:LabelResources.Name}" Width="Auto" HeaderContainerStyle="{DynamicResource GridViewHeaderStyle}">
        <GridViewColumn.CellTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding Name}" HorizontalAlignment="Left"/>
            </DataTemplate>
        </GridViewColumn.CellTemplate>
    </GridViewColumn>             
</GridView>

我能做什么?

听起来您只创建了一个 CustomGridView 实例,而您正试图将其分配到多个位置,这导致了异常。

根据MSDN page on x:Shared

In WPF, x:Shared is only valid under the following conditions:

  • The ResourceDictionary that contains the items with x:Shared must be compiled. The ResourceDictionary cannot be within loose XAML or used for themes.

  • The ResourceDictionary that contains the items must not be nested within another ResourceDictionary. For example, you cannot use x:Shared for items in a ResourceDictionary that is within a Style that is already a ResourceDictionary item.

我不太确定编译的 ResourceDictionary 是什么意思,但您可以尝试将构建操作更改为页面而不是资源,例如 this answer suggests

如果您无法使 x:Shared 正常工作,那么或许可以考虑将 SuggestionsView 改为 ContentTemplateDataTemplate,这样每次使用它都会创建自己的 GridView .

<ContentTemplate x:Key="CustomGridView">
    <GridView>
        <GridViewColumn Header="{x:Static resources:LabelResources.Name}" Width="Auto" HeaderContainerStyle="{DynamicResource GridViewHeaderStyle}">
            <GridViewColumn.CellTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding Name}" HorizontalAlignment="Left"/>
                </DataTemplate>
            </GridViewColumn.CellTemplate>
        </GridViewColumn>             
    </GridView>
</ContentTemplate>