Results 1 to 2 of 2

Thread: [RESOLVED] WPF Contextmenu databinding issues

  1. #1

    Thread Starter
    Frenzied Member
    Join Date
    May 2002
    Posts
    1,602

    Resolved [RESOLVED] WPF Contextmenu databinding issues

    Hi!
    I have a button where I want a context menu to appear. But for some reason I can't get the databinding correct. To figure this out, I created a small sample project:

    Here is the ViewModel
    Code:
    namespace WpfApplication1.ViewModel
    {
        public class Person
        {
            public string Name { get; set; }
            public int Age { get; set; }
        }
    
        public class WpfViewModel
        {
            public IEnumerable<Person> PersonList
            {
                get
                {
                    var li = new List<Person>()
                       {
                           new Person(){Name="Kalle", Age=12},
                           new Person(){Name="Nisse", Age=14},
                           new Person(){Name="Stina", Age=33}
                       };
                    return li;
                }
            }
    
        }
    }
    And here is the xaml:
    Code:
    <Window x:Class="WpfApplication1.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:n="clr-namespace:WpfApplication1.ViewModel"
            Title="MainWindow" Height="350" Width="525">
        <Window.DataContext>
            <n:WpfViewModel />
        </Window.DataContext>
    
        <Grid HorizontalAlignment="Center" VerticalAlignment="Center">
            <Button Width="60" Height="30" Content="Click me">
                <Button.ContextMenu>
                    <ContextMenu ItemsSource="{Binding PersonList}" DataContext="{Binding}">
                        <MenuItem Header="{Binding Name}"></MenuItem>
                    </ContextMenu>
                </Button.ContextMenu>
            </Button>
        </Grid>
    </Window>
    I have tried various ways to get the items to appear in the context menu:

    * Set datacontext explicitly on the ContextMenu

    * removed the DataContext property on the Context Menu

    * Used the Path overload on the binding method

    How can I make the above code work properly showing the different Persons names?

    /S

  2. #2

    Thread Starter
    Frenzied Member
    Join Date
    May 2002
    Posts
    1,602

    Re: WPF Contextmenu databinding issues

    I solved this issue by removing the menuitem and used a template instead, then databinding worked

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width