我有一个名为
问题在于动态添加的菜单项会生成以下数据绑定错误: 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') 主菜单的XAML声明类似于这样:
以下代码可以在运行时向可观察集合中添加文件夹:
我成功地把问题追溯到了一个在MenuItem样式中声明但未在我的应用程序中声明的绑定。我猜它是菜单项的默认样式...
其他菜单项似乎没有应用相同的样式时出现任何绑定问题。
所以我认为问题可能出在我的动态添加MenuItems的方式上。更具体地说,似乎是在将项目添加到ItemsControl之前就已经给MenuItem应用了样式。
到目前为止,我只想到了在将MenuItem添加到可观察集合之前,在代码中设置HorizontalContentAlignment属性,但这只是一种权宜之计,实际上掩盖了真正的问题。
mnuMainMenu
的主菜单,其中包含多个子菜单。其中一个子菜单mnuMostRecentDirs
本身又是另一个菜单,其项使用绑定到ObservableCollection的ItemSource属性在运行时生成。基本上它显示了最近使用的文件夹列表。问题在于动态添加的菜单项会生成以下数据绑定错误: 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') 主菜单的XAML声明类似于这样:
<!-- Main Menu -->
<Menu x:Name="mnuMainMenu" Height="Auto" IsMainMenu="True">
<!--- ... more menu declarations before ... -->
<MenuItem x:Name="mnuitemWorkDirs" Header="Directories">
<MenuItem x:Name="mnuNewDir"
Header="New"
Style="{StaticResource MenuItem}"
Command="{x:Static cmds:Commands.NewDirectory}" />
<MenuItem x:Name="mnuCurrentDir"
Header="Current"
Style="{StaticResource MenuItem}"
Command="{x:Static cmds:Commands.CurrentDirectory}" />
<MenuItem x:Name="mnuMostRecentDirs"
Header="Recent Directories.."
Style="{StaticResource MenuItem}"
ItemsSource="{Binding ElementName=theMain, Path=MostRecentFoldersList}" />
</MenuItem>
<!--- ... more menu declarations after ... -->
</Menu>
以下代码可以在运行时向可观察集合中添加文件夹:
private void PopulateMostRecentFoldersList(string[] paths)
{
MostRecentFoldersList.Clear();
if (paths == null)
return;
foreach (var fullPath in paths)
{
var mi = new MenuItem();
mi.Command = Commands.ChooseWorkingDirectory;
mi.CommandParameter = fullPath;
string name = System.IO.Path.GetFileName(fullPath);
mi.Header = name.ToUpper();
// removing this style completely
// or manually setting the HorizontalContentAlignment property here
// prevents the binding error from happening
mi.Style = (Style)FindResource("MenuItem");
MostRecentFoldersList.Add(mi);
}
}
我成功地把问题追溯到了一个在MenuItem样式中声明但未在我的应用程序中声明的绑定。我猜它是菜单项的默认样式...
其他菜单项似乎没有应用相同的样式时出现任何绑定问题。
所以我认为问题可能出在我的动态添加MenuItems的方式上。更具体地说,似乎是在将项目添加到ItemsControl之前就已经给MenuItem应用了样式。
到目前为止,我只想到了在将MenuItem添加到可观察集合之前,在代码中设置HorizontalContentAlignment属性,但这只是一种权宜之计,实际上掩盖了真正的问题。