WPF、TreeViewのデータ削除や入れ替えでバインドエラーが出るときは
エラー内容
System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.ItemsControl', AncestorLevel='1''. BindingExpression:Path=HorizontalContentAlignment; DataItem=null; target element is 'TreeViewItem' (Name=''); target property is 'HorizontalContentAlignment' (type 'HorizontalAlignment')
System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.ItemsControl', AncestorLevel='1''. BindingExpression:Path=VerticalContentAlignment; DataItem=null; target element is 'TreeViewItem' (Name=''); target property is 'VerticalContentAlignment' (type 'VerticalAlignment')
対策
青色のところを付け加えただけ
TreeViewのRisourcesとTreeViewのItemContainerStyleの両方において、
TreeViewItemのStyleの
VerticalContentAlignmentと
HorizontalContentAlignmentの
Valueに適当な値を指定する(今回はCenterにした)
要はバインドエラーが出ているところをStyleで決め打ちしているようだけど、よくわからん
結果
エラーがあってもなくても動作に変わりはなさそうなんだけど、気分がいい
参照したところ
akjoshi's Blog - Resolving harmless binding errors in WPF
weblogs.asp.net
こちらはcomboboxの場合
wpf - Cannot find source for binding with reference 'RelativeSource FindAncestor - Stack Overflow
stackoverflow.com
こちらもcomboboxの場合
変数 - wpf オブジェクト バインド - 入門サンプル
https://code-examples.net/ja/q/2d7ebe
こちらはTreeViewだけど、この方法だけでは解決できなかった(理解できなかった)
エラーの説明で検索すると出てくるのはcomboboxの場合ばかりでTreeViewがない、あっても同じ方法では解決できなくて、comboboxの対処方法と組み合わせたら解決できた
エラーが出るタイミングはバインドしているデータを削除した直後か、削除後に別のデータに入れ替えた直後
検索した感じで対処法ばかりなのでバグみたい、でも昔からあるようなので仕様なのかも