--- name: designing-wpf-customcontrol-architecture description: "Designs stand-alone control styles using WPF CustomControl and ResourceDictionary. Use when creating reusable custom controls or organizing control themes in Generic.xaml." --- # XAML Code Writing - WPF CustomControl A guide for using CustomControl and ResourceDictionary when writing XAML code in WPF. ## Project Structure The templates folder contains a WPF project example (use latest .NET per version mapping). ``` templates/ ├── WpfCustomControlSample.Controls/ ← WPF Custom Control Library │ ├── Properties/ │ │ └── AssemblyInfo.cs │ ├── Themes/ │ │ ├── Generic.xaml ← MergedDictionaries hub │ │ └── CustomButton.xaml ← Individual control style │ ├── CustomButton.cs │ ├── GlobalUsings.cs │ └── WpfCustomControlSample.Controls.csproj └── WpfCustomControlSample.App/ ← WPF Application ├── Views/ │ ├── MainWindow.xaml │ └── MainWindow.xaml.cs ├── App.xaml ├── App.xaml.cs ├── GlobalUsings.cs └── WpfCustomControlSample.App.csproj ``` ## Basic Principles **When generating XAML code, use CustomControl with Stand-Alone Control Style Resource through ResourceDictionary** **Purpose**: Fix the timing of StaticResource loading and minimize style dependencies ## WPF Custom Control Library Project Structure ### Default Structure When Creating Project ``` YourProject/ ├── Dependencies/ ├── Themes/ │ └── Generic.xaml ├── AssemblyInfo.cs └── CustomControl1.cs ``` ### Restructure to Recommended Project Structure ``` YourProject/ ├── Dependencies/ ├── Properties/ │ └── AssemblyInfo.cs ← Moved ├── Themes/ │ ├── Generic.xaml ← Use as MergedDictionaries hub │ ├── CustomButton.xaml ← Individual control style │ └── CustomTextBox.xaml ← Individual control style ├── CustomButton.cs └── CustomTextBox.cs ``` ## Step-by-Step Setup ### 1. Create Properties Folder and Move AssemblyInfo.cs - Create Properties folder in the project - Move AssemblyInfo.cs to the Properties folder ### 2. Configure Generic.xaml - Use as MergedDictionaries Hub Generic.xaml does not define styles directly; it only performs the role of merging individual ResourceDictionaries: ```xml ``` ### 3. Define Individual Control Styles Define styles in independent XAML files for each control: ```xml ``` ## Real Project Example ### Generic.xaml Example ```xml ``` ### Individual Control Style Example ```xml ``` ## Advantages - Each control's style is separated into independent files for easier management - Generic.xaml simply performs a merging role, making the structure clear - StaticResource reference timing is clear and dependencies are minimized - Work can be split by file for team collaboration