DataContext

De Banane Atomic
Révision datée du 16 avril 2020 à 12:32 par Nicolas (discussion | contributions)
(diff) ← Version précédente | Voir la version actuelle (diff) | Version suivante → (diff)
Aller à la navigationAller à la recherche

Dans le code behind de la vue

Csharp.svg
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        this.DataContext = new MainWindowVM();
    }

Dans la vue

Xaml.svg
<Window x:Class="WpfApplication1.MainWindow"
        xmlns:local="clr-namespace:WpfApplication">
    <Window.DataContext>
        <local:MainWindowVM />  <!-- appel le ctor par défaut de MainWindowVM -->
    </Window.DataContext>

Via une StaticResource

Xaml.svg
<Window x:Class="WpfApplication1.MainWindow"
        xmlns:local="clr-namespace:WpfApplication"
        DataContext="{Binding Source={StaticResource ResourceKey=MainVM}}">
    <Window.Resources>
        <local:MainWindowVM x:Key="MainWindowVM" />
    </Window.Resources>

Design

Définit quel sera le type du DataContext afin de faciliter le développement (auto-completion).

Xaml.svg
<Window xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:local="clr-namespace:WpfItemsControl"
        d:DataContext="{d:DesignInstance local:MainWindowVM}">