MenuItem added programmatically causes Binding error

前端 未结 2 1367
后悔当初
后悔当初 2021-01-18 03:10

I have a main menu mnuMainMenu consisting of several sub-menus. One of the sub-menus mnuMostRecentDirs is itself another menu that has it\'s items

相关标签:
2条回答
  • 2021-01-18 03:48

    I really think it's not a good idea or ""WPF compatible"" to add UIelemnts from code.

    I would suggest something like this:

        <Menu>
            <MenuItem Header="MainMenu" Name="sampleMenu">
                <MenuItem.ItemTemplate>
                    <DataTemplate>
                        <MenuItem Header="{Binding Path=PathtoNameOfRecentDocObject}"/>
                    </DataTemplate>
                </MenuItem.ItemTemplate>
            </MenuItem>
        </Menu>
    

    and set MainMenu's ItemsSource to MostRecentFoldersList

    0 讨论(0)
  • 2021-01-18 03:50

    As pointed out by @LPL - it turns out this is a known (acknowledged) problem in the WPF framework. Based on information found on MSDN support forums here and here, it appears that when setting the ItemsSource of a MenuItem to a collection of MenuItems it doesn't handle things in the correct order

    Per MSDN Support staff:

    This happens when you set MenuItem.ItemsSource to a Collection that contains MenuItems. This error has already been handled internally, so you can just leave it alone.

    Or you can explicit set MenuItem.HorizontalContentAlignment property and VerticalContentAlignment property to avoid this error. You can simply put the following code in application.Resource to achieve this.

      <Style TargetType="MenuItem">
       <Setter Property="HorizontalContentAlignment" Value="Left"/>
       <Setter Property="VerticalContentAlignment" Value="Center"/>
      </Style>
    

    I hope this helps others having the same issue.

    0 讨论(0)
提交回复
热议问题