Cannot find source for binding with reference を解決
現在仕事でWPFを扱っているのですが、動的な右クリックメニューを生成しているViewModelで、以下のような警告が出た。
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 'MenuItem' (Name=''); target property is 'HorizontalContentAlignment' (type 'HorizontalAlignment')
以下のようにMenuItemにStyleを指定したところ、解消できた。
・ View.xaml
<Style x:Key="MenuItemStyle" TargetType="MenuItem"><Setter Property="HorizontalAlignment" Value="Stretch"/><Setter Property="VerticalAlignment" Value="Center"/><Setter Property="HorizontalContentAlignment" Value="Stretch"/><Setter Property="VerticalContentAlignment" Value="Center"/></Style>
・View.xaml.cs
var menuStyle = (Style)this.FindResource("MenuItemStyle");
・ViewModel.cs
var item = new MenuItem { Header = "貼り付け", Style = menuStyle };
・参考サイト