c# - 如何根据绑定(bind)属性动态更改 ContentTemplate?

标签 c# wpf

我一直有一个问题困扰了我一段时间,但我相信我终于找到了它。症状是,当我的绑定(bind)属性之一触发换出 ContentTemplateDataTrigger 时,我的 WPF 控件将无法正确呈现。堆栈跟踪:

  System.ArgumentNullException: Value cannot be null.
  Parameter name: d
     at MS.Internal.Data.ElementObjectRef.GetObject(DependencyObject d, ObjectRefArgs args)
     at MS.Internal.Data.ObjectRef.GetDataObject(DependencyObject d, ObjectRefArgs args)
     at System.Windows.Data.BindingExpression.MS.Internal.Data.IDataBindEngineClient.VerifySourceReference(Boolean lastChance)
     at MS.Internal.Data.DataBindEngine.Task.Run(Boolean lastChance)
     at MS.Internal.Data.DataBindEngine.Run(Object arg)
     at MS.Internal.Data.DataBindEngine.OnLayoutUpdated(Object sender, EventArgs e)
     at System.Windows.ContextLayoutManager.fireLayoutUpdateEvent()
     at System.Windows.ContextLayoutManager.UpdateLayout()
     at System.Windows.ContextLayoutManager.UpdateLayoutCallback(Object arg)
     at System.Windows.Media.MediaContext.InvokeOnRenderCallback.DoWork()
     at System.Windows.Media.MediaContext.FireInvokeOnRenderCallbacks()
     at System.Windows.Media.MediaContext.RenderMessageHandlerCore(Object resizedCompositionTarget)
     at System.Windows.Media.MediaContext.RenderMessageHandler(Object resizedCompositionTarget)
     at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
     at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)

调试器根本没有帮助,因为它只是在 application.Run() 上中断。这是我在实际 xaml 方面所做的事情:

  <CollectionViewSource x:Key="SomeCollectionView"
                        Source="{Binding StatsByUser}"
                        IsLiveSortingRequested="True">
      <CollectionViewSource.SortDescriptions>
          <scm:SortDescription PropertyName="Amount" Direction="Descending"/>
          <scm:SortDescription PropertyName="Name" Direction="Ascending"/>
      </CollectionViewSource.SortDescriptions>
  </CollectionViewSource>

  <ItemsControl Background="Transparent" Width="{StaticResource Width}"
                ItemsSource="{Binding Source={StaticResource SomeCollectionView}}">
      <ItemsControl.Resources>
          <DataTemplate x:Key="FullViewTemplate">
              <Border Style="{StaticResource BorderStyle}">
                  <controls:FullCustomEntityControl CustomEntityObject="{Binding}"
                                                  Style="{StaticResource PanelStyle}"
                                                  MouseDown="Info_OnMouseDown"/>
              </Border>
          </DataTemplate>
          <DataTemplate x:Key="CompactViewTemplate">
              <Border Style="{StaticResource BorderStyle}">
                  <controls:CompactCustomEntityControl CustomEntityObject="{Binding}"
                                                     Style="{StaticResource PanelStyle}"
                                                     MouseDown="Info_OnMouseDown"/>
              </Border>
          </DataTemplate>
      </ItemsControl.Resources>
      <ItemsControl.ItemTemplate>
          <DataTemplate>
              <ContentControl Content="{Binding}">
                  <ContentControl.Style>
                      <Style TargetType="{x:Type ContentControl}">
                          <Setter Property="ContentTemplate" Value="{StaticResource FullViewTemplate}"/>
                          <Style.Triggers>
                              <DataTrigger Binding="{Binding RelativeSource={RelativeSource AncestorType=c:ShellView}, Path=ViewModel.ShowCompactView}" Value="True">
                                  <Setter Property="ContentTemplate" Value="{StaticResource CompactViewTemplate}"/>
                              </DataTrigger>
                          </Style.Triggers>
                      </Style>
                  </ContentControl.Style>
              </ContentControl>
          </DataTemplate>
      </ItemsControl.ItemTemplate>
  </ItemsControl>

每当 ViewModel.ShowCompactView 引发 PropertyChanged 事件并启动 DataTrigger 时,它会切换 ContentTemplate,然后抛出这个错误。是否有解决此问题的方法或更好的方法来构建不会导致此问题的 ContentTemplate 交换?

编辑:可能相关的支持文章 https://support.microsoft.com/en-us/kb/2461678

Edit2:UI 发生的情况示例:enter image description here .您可以看到大槽是 FullCustomEntityControl,小槽是 CompactCustomEntityControl。让它们处于任一模式而不更改它不会导致任何问题,但是让数据触发器更改它们会导致这样的问题。另外,使用的控件应该是一致的,而不是这里看起来像 split 的东西。让它们处于任一模式,我的意思是只删除数据触发器并选择一个或另一个。

Edit3:关于类似问题的帖子,来自 Microsoft 的人回复:https://social.msdn.microsoft.com/Forums/vstudio/en-US/fb4d0f41-bfea-409f-b8ac-e66558984b7a/argumentnullexception-when-displaying-wpf-window?forum=wpf

相关信息:

If you're getting an ArgumentNullException with VerifySourceReference on the stack, it is definitely caused by the issue described in Connect 561752. Even if your app is not using ElementName bindings directly, it may use them indirectly - several built-in controls use ElementName bindings: ComboBox, ContextMenu, MenuItem, etc.

最佳答案

每个 ItemsControl 都有 ItemTemplateSelector 属性(property),您可以利用这一点。

关于c# - 如何根据绑定(bind)属性动态更改 ContentTemplate?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41134401/

相关文章:

c# - 在 C# 中,如何将刷新/重绘消息发送到 WPF 网格或 Canvas ?

c# - Process.Start() 问题 - 未显示 GUI

c# - 比较数据集或更好的想法

c# - Unity 在运行时更改 Sprite 渲染器中的 Sprite

c# - 如何使用表达式树创建一个空委托(delegate)?

c# - WPF 数据网格在不应该刷新时自行刷新

c# - WCF 数据服务 : MaxProtocolVersion set at v2 despite Service set at v3. 在 OfType() 上结束抛出错误

c# - EF6,延迟加载未按预期工作

wpf - 如何将颜色绑定(bind)到文本框背景wpf

wpf - 刷新 ObjectDataProvider 时 View 丢失