Hi Rajeev,
The quick way to fix this is to replace it with XamlReader.Load(string) method. However, this will not work if :
- The control XAML includes event handlers. (XamlReader.Load() does not hook up events.)
- The control XAML includes names. (XamlReader.Load() does not create a new namescope.)
The recommended way to do this is:
BEFORE:
public class MyControl : Control
{
public MyControl() : base()
{
System.IO.Stream s = this.GetType().Assembly.GetManifestResourceStream("MyNamespace.UserControl1.xaml");
FrameworkElement content = this.InitializeFromXaml(new System.IO.StreamReader(s).ReadToEnd());
this.namedElement = (Rectangle) content.FindName("namedElement");
}
private Rectangle namedElement; // xaml contains x:Name="namedElement"
}
<Grid
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
>
<Rectangle x:Name="namedElement"/>
<Ellipse />
</Grid>
AFTER:
public class MyControl : UserControl
{
public MyControl() : base()
{
// if building outside VS
Application.LoadComponent(this, new Uri("MyApp;component/MyControl.xaml", UriKind.Relative));
FrameworkElement content = this.Content;
this.namedElement = (Rectangle) content.FindName("namedElement");
}
private Rectangle namedElement; // xaml contains x:Name="namedElement"
}
<UserControl x:Class="Namespace.MyControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
>
<Grid>
<Rectangle x:Name="namedElement"/>
<Ellipse />
</Grid>
</UserControl>
If you use VS to compile, it will generate a partial class for you so that all you need to do is call InitializeComponent:
public partial class MyControl : UserControl
{
public MyControl() : base()
{
InitializeComponent();
}
}
Hope this helps.
Adrian Mascarenhas
Microsoft
This post is provided "as-is"