Ask Learn
Preview
Ask Learn is an AI assistant that can answer questions, clarify concepts, and define terms using trusted Microsoft documentation.
Please sign in to use Ask Learn.
Sign inThis browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Loading XAML at run time is really simple. I wrote a small sample to load the XAML at run time and than attach the event handler with the XAML object. I created following XAML page and copied it to the debug folder.
<Page
xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
Title="Page1">
<Grid>
<Button Margin="0,0,9,38" Name="button1" Height="82" HorizontalAlignment="Right" VerticalAlignment="Bottom" Width="132">Button</Button>
</Grid>
</Page>
and here is the C# code
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
LoadXAMLMethod();
}
Button ButtoninXAML;
public void LoadXAMLMethod()
{
try
{
StreamReader mysr = new StreamReader("Page1.xaml");
DependencyObject rootObject = XamlReader.Load(mysr.BaseStream) as DependencyObject;
ButtoninXAML = LogicalTreeHelper.FindLogicalNode(rootObject, "button1") as Button ;
ButtoninXAML.Click += new RoutedEventHandler(Button_Click);
this.Content = rootObject;
}
catch (FileNotFoundException ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
public void Button_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("Hi WPF");
}
}
}
do not forget to add following namespaces.
using System.IO;
using System.Windows.Markup;
Ask Learn is an AI assistant that can answer questions, clarify concepts, and define terms using trusted Microsoft documentation.
Please sign in to use Ask Learn.
Sign in