wpfxamlxamlreader

XamlReader with Click Event


I am using XamlReader in my WPF project. And it works (My reference)

My current sample Xaml is like that:

<Grid xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" Width="800" Height="600">
  <Button Name="Test1" Content="Test1" Width="357" Height="88" Margin="14,417,0,0" ></Button>
  <Button Name="Test2" Content="Test2" Width="357" Height="88" Margin="14,529,0,0" ></Button>
</Grid>

and adding button's click event like this:

button = LogicalTreeHelper.FindLogicalNode(rootObject, "Test1") as Button ;
button.Click += new RoutedEventHandler(Button1_Click);

Is it possible to write xaml like this?

<Grid xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" Width="800" Height="600">
  <Button Name="Test1" Content="Test1" ... Click="Button1_Click"></Button>
  <Button Name="Test2" Content="Test2" ... Click="Button2_Click"></Button>
</Grid>

Solution

  • XamlReader.Load not allowed to attach eventHandlers in it. so use this technique to dynamically attach the eventHandlers to it.

    1- Write your Xaml string without eventHandlers -But write the Name property of those Controls.

    2- Load the string with XamlReader.Load(str);

    3- Then load the content of DataTemplate from it. using Grid template = ((Grid)(dt.LoadContent()));

    Note: here Grid is the parent Control in DataTemplate.

    4- Find the Control by Name you want to attach the Event Handler. Button img = (Button)template.FindName("MyButtonInDataTemplate");

    I hope it helps.