# XAML Performance / Tối Ưu XAML
Hướng dẫn chi tiết về Compiled Bindings, layout optimization và XAML best practices.
## Core Principles / Nguyên Tắc Cốt Lõi
1. **Compiled Bindings**: Luôn sử dụng `x:DataType` để binding tại compile-time
2. **Flat Layouts**: Tránh nested layouts, ưu tiên Grid
3. **Virtualization**: Sử dụng CollectionView cho danh sách lớn
---
## Compiled Bindings (BẮT BUỘC)
### Why Compiled Bindings?
| Aspect | Reflection Binding | Compiled Binding |
|--------|-------------------|------------------|
| Performance | Slow (runtime lookup) | Fast (compile-time) |
| Error Detection | Runtime exceptions | Compile-time errors |
| NativeAOT | May not work | Full support |
| Intellisense | No | Yes |
### Basic Pattern
```xml
```
```xml
```
### Nested DataType Changes
```xml
```
### Binding to Parent ViewModel from ItemTemplate
```xml
```
---
## Layout Optimization
### Grid vs Nested StackLayout
```xml
```
### Layout Performance Tips
```xml
```
---
## CollectionView Best Practices
### Virtualization (Auto-enabled)
```xml
```
### EmptyView và Loading States
```xml
```
---
## Resource Dictionary Patterns
### App-level Resources
```xml
```
### Colors.xaml
```xml
#6750A4
#381E72
#625B71
#1C1B1F
#49454F
#FFFBFE
#E7E0EC
#4CAF50
#FF9800
#B3261E
```
### Styles.xaml
```xml
```
### Usage in Pages
```xml
```
---
## Hot Reload Tips
```xml
```
---
## Common Mistakes / Lỗi Thường Gặp
### 1. Missing x:DataType in ItemTemplate
```xml
```
### 2. Image Not Caching
```xml
```
### 3. Heavy Work in Converters
```csharp
// ❌ SAI: Slow converter
public object Convert(object value, ...)
{
// Heavy computation on UI thread!
return ProcessData(value);
}
// ✅ ĐÚNG: Pre-compute in ViewModel
[ObservableProperty]
private string _processedValue; // Already computed
```
---
## Performance Checklist
- [ ] `x:DataType` declared on every page and DataTemplate
- [ ] No nested StackLayout deeper than 2 levels
- [ ] CollectionView used for lists (not StackLayout)
- [ ] Fixed sizes where possible (WidthRequest, HeightRequest)
- [ ] Image caching enabled for remote images
- [ ] Styles in ResourceDictionary, not inline
- [ ] StaticResource over DynamicResource when possible
---
## Resources
- [.NET MAUI Performance Best Practices](https://learn.microsoft.com/en-us/dotnet/maui/deployment/performance)
- [Compiled Bindings](https://learn.microsoft.com/en-us/dotnet/maui/fundamentals/data-binding/compiled-bindings)
- [MVVM Rules](./mvvm-rules.md)
- [DI Setup](./di-setup.md)