Using Events / Commands with XamlReader

I am dynamically creating my data file using XamlReader.Parse (string). The problem is that I cannot put any events in any controls that I create using XamlReader. After doing some research on the Internet, I found out that this is a known limitation of XamlReader.

I don’t know much about commands in WPF, but can I somehow use them to get the same result? If so, how? If not, can I handle the event in my code behind the control created with Xaml Reader?

The following is an example of a data file created. I have a MenuItem_Click event handler defined in the window code that will host this data file.

When I try to start it, the following error occurs: System.Windows.Markup.XamlParseException was unhandled: it was not possible to create a 'Click' from the text 'MenuItem_Click'.

DataTemplate result = null;
        StringBuilder sb = new StringBuilder();

        sb.Append(@"<DataTemplate 
                        xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'
                        xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>
                            <Grid Width=""Auto"" Height=""Auto"">

                            <TextBlock Text=""Hello"">
                                <TextBlock.ContextMenu>
                                    <ContextMenu>
                                         <MenuItem 
                                          Header=""World""
                                          Click=""MenuItem_Click""></MenuItem>
                                    </ContextMenu>
                                </TextBlock.ContextMenu>
                            </TextBlock>

                            </Grid>
                      </DataTemplate>");

        result = XamlReader.Parse(sb.ToString()) as DataTemplate;
+3
source share
2 answers

Hoping that a late answer might help others:

I found that I needed to bind events after parsing and had to remove the click event from the Xaml line.

DataTemplate ItemTemplate, ItemSource . , click , , .

//Set the datatemplate to the result of the xaml parsing.
myListView.ItemTemplate = (DataTemplate)result;

//Add the itemtemplate first, otherwise there will be a visual child error
myListView.ItemsSource = this.ItemsSource; 

//Attach click event.
myListView.AddHandler(MenuItem.ClickEvent, new RoutedEventHandler(MenuItem_Click));

click , ListView DataTemplate.

internal void MenuItem_Click(object sender, RoutedEventArgs e){
    MenuItem mi = e.OriginalSource as MenuItem;
    //At this point you can access the menuitem header or other information as needed.
}
+5

. Parse. # dev, , , , - if-all-else-fail:

XAML Click .. FindLogicalNode , .

, , MenuItem ID="WorldMenuItem". :

MenuItem worldMenuItem = (MenuItem)LogicalTreeHelper.FindLogicalNode(result, "WorldMenuItem");
worldMenuItem.Click += MenuItem_Click; // whatever your handler is
0

Source: https://habr.com/ru/post/1760764/


All Articles