Is there any recommended way with WPF to create a common window style to be used across an application? I have several dialogs that appear in my app, and I would like them a
To add to H.B.'s very helpful post, you may want to connect your event handlers in the loaded event as he's done but instead of using anonymous methods or lambda expressions, consider connecting them to protected virtual methods which can be overridden in the derived class should the functionality need to vary. In my case, I created a base data entry form which has buttons for saving and cancelling:
public DataEntryBase()
{
Loaded += (_, __) =>
{
var saveButton = (Button)Template.FindName("PART_SaveAndCloseButton", this);
var cancelButton = (Button)Template.FindName("PART_CancelButton", this);
saveButton.Click += SaveAndClose_Click;
cancelButton.Click += Cancel_Click;
};
}
protected virtual void SaveAndClose_Click(object sender, RoutedEventArgs e) { DialogResult = true; }
protected virtual void Cancel_Click(object sender, RoutedEventArgs e) { }
The save functionality is then overridden in each derived class to save the specific entity:
protected override void SaveAndClose_Click(object sender, RoutedEventArgs e)
{
if (Save())
{
base.SaveAndClose_Click(sender, e);
}
}
private bool Save()
{
Contact item = contactController.SaveAndReturnContact((Contact)DataContext);
if (item!=null)
{
DataContext = item;
return true; }
else
{
MessageBox.Show("The contact was not saved, something bad happened :(");
return false;
}
}