Tôi có một thanh công cụ với 3 DataTemplates cho mục của tôi:ObservableCollection.CollectionChanged không chọn DataTemplate đúng trên 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>
Các ItemsSource là một ObservableCollection < đối tượng >
Ba mục đầu tiên đã có sẵn trong hàm tạo của ViewModel của tôi, ba hàm này sử dụng DataTemplates như mong đợi.
Nếu tôi thêm một "SimpleContextActionViewModel" khác vào ObservableCollection, thanh công cụ chỉ thêm một ContentPresenter gọi ToString. Nếu tôi thêm các dòng sau vào reasign ObservableCollection để một hình mới, mọi thứ hoạt động tốt:
this.ContextActions = new ObservableCollection<object>(this.ContextActions);
này gây nên việc thực hiện NotifyPropertyChanged của ViewModel của tôi và tất cả các mục được tái tạo và tìm kiếm tốt.
Tại sao một CollectionChanged của ObservableCollection của tôi không chọn DataTemplate hợp lệ trong khi PropertyChanged làm gì ?.
Đây là cách nó trông
Tôi sẽ thử điều đó vào ngày mai, mặc dù nó cảm thấy thực sự bẩn để quản lý các mẫu dữ liệu cụ thể ở cấp ứng dụng. – Console
@Console không chắc chắn chính xác lý do tại sao phương pháp tiếp cận chuẩn không hoạt động. Tôi tình cờ gặp điều này đôi khi trước đây. Nếu bạn muốn có một giải pháp khác, bạn có thể thử thực hiện một ItemTemplateSelector và xem liệu bạn có thể gán DataTemplates theo cách đó không? – Krishna