Quantcast
Channel: VBForums - WPF, WCF, WF
Viewing all articles
Browse latest Browse all 256

[RESOLVED] WPF Contextmenu databinding issues

$
0
0
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

Viewing all articles
Browse latest Browse all 256

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>