Search code examples
c#wpfpartial-classescode-readability

C# partial class for WPF Controls events for more readability


For a long time I used partial classes to put in the events of my WPF controls for more readability, is this a good practice?

Example
MainWindow.xaml

<Button x:Name="SubmitBtn" Click="SubmitBtn_Click">
    Submit
</Button>

MainWindow.xaml.cs

public void Submit(){
    //Submit action
}

EventsMainWindow.cs

public partial class MainWindow {
    private void SubmitBtn_Click(object sender, RoutedEventArgs e) {
        Submit();
    }
}

So is this a good practice?
Thanks for your answers.


Solution

  • Well I would definitely look into the use of Commands instead because the design pattern of MVVM would (could) become a better solution than the path you are about to go with here. MVVM will at first look way more complicated to begin with than the fast and easy way of handling everything in your code behind file (*.xaml.cs). But if your application will evolve over time and needs extensions then you really should consider your architecture at the beginning. An IoC container would be a good thing to look into i guess...

    Check out:

    Basic MVVM and ICommand Usage Example

    how to use MVVMLight SimpleIoc?

    Nuget packages to research:

    MVVMLight -> RelayCommand and IoC

    MahApps -> look/ui/basic features