ObservableCollection.CollectionChanged未在ToolBar上选择正确的DataTemplate

Con*_*ole 6 c# wpf datatemplate

我的项目有一个带有3个DataTemplates的ToolBar:

  <ToolBar ItemsSource="{Binding ContextActions}" Background="Transparent" ToolBarTray.IsLocked="True">
        <ToolBar.Resources>
            <DataTemplate DataType="{x:Type viewModels:SimpleContextActionViewModel}">
                <Button Command="{Binding ActionCommand}" Style="{StaticResource ToolBarButtonStyle}" ToolTip="{userInterface:Translation Binding={Binding ToolTip}}">
                    <ContentControl Template="{Binding Icon,Converter={StaticResource NameToResourceConverter}}" Margin="5" />
                </Button>
            </DataTemplate>
            <DataTemplate DataType="{x:Type viewModels:SeparatorViewModel}">
                <Rectangle Fill="{StaticResource SeparatorBrush}" Width="1" VerticalAlignment="Stretch" Margin="2,7" />
            </DataTemplate>
            <DataTemplate DataType="{x:Type viewModels:PopupContextActionViewModel}">
                <Grid>
                    <ToggleButton IsChecked="{Binding ElementName=ContextActionPopup, Mode=TwoWay,Path=IsOpen}" Style="{StaticResource ToolBarButtonStyle}"
                                  ToolTip="{userInterface:Translation Binding={Binding ToolTip}}">
                        <ContentControl Template="{Binding Icon, Converter={StaticResource NameToResourceConverter}}" Margin="5" />
                    </ToggleButton>
                    <Popup Name="ContextActionPopup" Height="150" Width="150" StaysOpen="False">
                        <Border BorderBrush="{StaticResource PopupBorderBrush}" BorderThickness="1" Background="White">
                            <ContentControl userInterface:RegionHelper.RegionName="{Binding RegionId}" />
                        </Border>
                    </Popup>
                </Grid>
            </DataTemplate>
        </ToolBar.Resources>
    </ToolBar>
Run Code Online (Sandbox Code Playgroud)

ItemsSource是一个ObservableCollection <object>

前三个项目已在我的ViewModel的构造函数中可用,这三个项目按预期使用DataTemplates.

如果我向ObservableCollection添加另一个"SimpleContextActionViewModel",ToolBar只会添加一个调用ToString的ContentPresenter.如果我添加以下行来重新设置ObservableCollection到一个新的,一切正常:

this.ContextActions = new ObservableCollection<object>(this.ContextActions);
Run Code Online (Sandbox Code Playgroud)

这会触发我的ViewModel的NotifyPropertyChanged实现,并重新创建所有项目并且看起来很好.

为什么我的ObservableCollection的CollectionChanged在PropertyChanged没有选择有效的DataTemplate?

这是它的外观 这是它的外观

Kri*_*hna 3

我以前见过这种情况发生在工具栏上,当与集合一起使用时,除了构造函数之外的任何地方都会发生更改。

不要将数据模板添加到工具栏资源中,而是将它们添加到 app.xaml 中,然后您将看到您的代码将正常工作。试试这个,如果仍然不起作用请告诉我