wpf create master detail view in csharp

To create a Master-Detail View in WPF, you can follow these steps:

  1. Create your ViewModels for both the Master and Detail Views.
  2. In your Master ViewModel, create an ObservableCollection or List of items that will act as the "Master" data.
  3. In your Master View, bind the ListView or DataGrid control to the Master ViewModel's ObservableCollection or List.
  4. Create your Detail View and ViewModel.
  5. In your Master View, bind the SelectedItem of the ListView or DataGrid to a property in the Master ViewModel that represents the currently selected item.
  6. In your Master ViewModel, create a Detail ViewModel property that is initialized with a new instance of the Detail ViewModel.
  7. In the Setter for the currently selected item property, set the Detail ViewModel's instance to the SelectedItem's corresponding detail data.
  8. In your Master View, create a ContentControl or other container element that will hold the Detail View.
  9. Bind the container element's content to the Detail ViewModel's View property.

Here's some sample code to get you started. This assumes you're using an MVVM pattern and that your Views and ViewModels are named appropriately (e.g. MyMasterView.xaml/MyMasterViewModel.cs):

main.cs
// MyMasterViewModel.cs
public class MyMasterViewModel : INotifyPropertyChanged
{
    public ObservableCollection<MyMasterItem> MasterItems { get; set; }
    public MyDetailViewModel DetailViewModel { get; set; }

    private MyMasterItem _selectedItem;
    public MyMasterItem SelectedItem
    {
        get { return _selectedItem; }
        set
        {
            _selectedItem = value;
            DetailViewModel.DetailData = _selectedItem.DetailData;
            OnPropertyChanged(nameof(SelectedItem));
        }
    }

    // INotifyPropertyChanged implementation omitted for brevity
}

// MyMasterView.xaml
<ListView ItemsSource="{Binding MasterItems}"
          SelectedItem="{Binding SelectedItem}">
    <ListView.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding ItemData}"/>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>
<ContentControl Content="{Binding DetailViewModel.View}"/>

// MyDetailViewModel.cs
public class MyDetailViewModel : INotifyPropertyChanged
{
    public object DetailData { get; set; }

    public UserControl View => new MyDetailView();

    // INotifyPropertyChanged implementation omitted for brevity
}

// MyDetailView.xaml (your actual Detail View)
<UserControl>
    <TextBlock Text="{Binding DetailData}"/>
</UserControl>
1307 chars
47 lines

gistlibby LogSnag