This sounds like it should be simple. I have a Page
declared in XAML in the normal way (i.e. with "Add new item...") and it has a custom property. I\'
Answer relates to Silverlight.
There is no simple obvious way to use plain property in the way you want, there will have to be some compromise along the way.
Doesn't really work:-
Some suggest a dependency property. That won't work, its still a public property from Xaml POV. An attached property will work but that would make working with it in code ugly.
Close but no banana:-
The Xaml and the class can be fully separated like this:-
Code:-
public class PageWithProperty : Page
{
internal System.Windows.Controls.Grid LayoutRoot;
private bool _contentLoaded;
public void InitializeComponent()
{
if (_contentLoaded) {
return;
}
_contentLoaded = true;
System.Windows.Application.LoadComponent(this, new System.Uri("/StackoverflowSpikes;component/PageWithProperty.xaml", System.UriKind.Relative));
this.LayoutRoot = ((System.Windows.Controls.Grid)(this.FindName("LayoutRoot")));
}
public PageWithProperty()
{
InitializeComponent();
}
void PageWithProperty_Loaded(object sender, RoutedEventArgs e)
{
MessageBox.Show("Hi");
}
public string Message {get; set; }
}
However you lose some support from the designer. Notably you will have to create the fields to hold references to named elements and assign them yourself in your own implementation of InitialiseComponent
(IMO all these automatic fields for named items isn't necessarily a good thing anyway). Also the designer won't create event code dynamically for you (although strangely it seems to know how to navigate to one you have manually created) however events defined in Xaml will be wired up at runtime.
IMO best option:-
The best compromise has already been posted by abhishek, use a shim base class to hold the properties. Minimul effort, maximum compatibility.