简体   繁体   中英

WPF Clicking on a dynamic menu item and returning the name?

I have a file menu, where on load, some menuItems are populated from filenames in a directory.

<MenuItem 
    x:Name="LayoutLoad" 
    Header="Load saved layout" 
    HorizontalAlignment="Left" 
    Width="200"
    />

//on load (code behind)

string[] filePaths = Directory.GetFiles("Settings/layouts");
for (int i = 0; i < filePaths.Count(); i++)
{
    MenuItem item = new MenuItem {
        Header = System.IO.Path.GetFileName(filePaths[i]),
        Name = System.IO.Path.GetFileName(filePaths[i])
    };
    item.Click += new RoutedEventHandler(Chooselayout);
    LayoutLoad.Items.Add(item);
}

My click event linked to the items is:

public void Chooselayout(Object sender, RoutedEventArgs e)
{

     string fileName = ((MenuItem)sender).Name;
     var serializer = new XmlLayoutSerializer(dockingManager);

     using (var stream = new StreamReader(fileName))
         serializer.Deserialize(stream);
}

the line string fileName = ((MenuItem)sender).Name; fails. Can I return the name of the clicked item in this way? Am I simply casting wrongly? Or going about this in the incorrect way?

Thank you.

The rules for element names in WPF are stricter than the rules for paths and file names. For example, I don't believe Name can contain spaces or slashes. I suggest you use Tag instead (and cast back to string in your handler).

Also, look at how you are listing your files:

Directory.GetFiles("Settings/layouts")

You are looking for files that exist in <working directory>/Settings/layouts/ . Yet, when you create your StreamReader , you are only giving it the name of the file, so it's going to look for the file in <working directory>/ . You need to give it the absolute path or the full relative path.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM