fc2ブログ

ComboBox in ControlTemplate

仕事でControlTemplateを組む事があり、その中にComboBoxを組み込む必要があった。
で、ComboBoxのドロップダウンメニューを出したうえで画面を終了すると、裏でバインドエラーが出るようになった。

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 'ComboBoxItem' (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 'ComboBoxItem' (Name=''); target property is 'VerticalContentAlignment' (type 'VerticalAlignment')

なんぞこれ?しかも質の悪いことに、コンボボックス内に表示したアイテム分発生している。100件のアイテムがあったら、上のエラー100個、合計200個のエラーが出ている事になる。このバインディングエラーというのが曲者で、パフォーマンスに悪影響を与えるものだ。調べてみたら、結構あった。
Resolving harmless binding errors in WPF
Combobox throwing Data Binding Error
ListBoxItem produces “System.Windows.Data Error: 4” binding error
最初のリンクにあった内容を引用すると

This is a "known" issue, and happens to all controls that contain dynamically created lists (all item controls i.e. ComboBox, menu, ListBox etc.). ControlTemplate of items in these controls (specifically MenuItem, ComboBoxItem etc.) try to find the nearest ItemsControl and bind to the VerticalAlignment and HorizonalAlignment properties and raises this error on not finding the source.

ComboBoxだけでなく、ListBox等、内容が動的に変わるコントロールに発生するらしい。解決策としては、Style設定をする事だそうだ。
<!-- ComboBox For Resolving Binding Error-->
<Style TargetType="ComboBoxItem">
<Setter Property="HorizontalAlignment" Value="Left"/>
<Setter Property="VerticalAlignment" Value="Center"/>
<Setter Property="HorizontalContentAlignment" Value="Left"/>
<Setter Property="VerticalContentAlignment" Value="Center"/>
</Style>
ま、解決策があるだけましか。.NET4.5でも試してみないとな。
スポンサーサイト



当サイトは基本をすっ飛ばしてます。基本文法等は、@ITをどうぞ
カテゴリー: WPF4 | コメント: 0 | トラックバック: 0


この記事へのコメント

コメントの投稿

非公開コメント


サイドバー背後固定表示サンプル

当ブログに書かれたソースコードは流用自由です。

バグ、スペルミス等はありうる事です。

ご利用の際は自己責任でお願いしますm(_ _)m