Skip to content

Latest commit

 

History

History

WpfAppNetCore

WPF sample

Create the IoC container, like here

public partial class App
{
    internal readonly IContainer Container = IoC.Container
        .Create()
        .Using<ClockConfiguration>()
        .Using<AppConfiguration>();

    protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);
        Container.Resolve<IMainWindowView>().Show();
    }

    protected override void OnExit(ExitEventArgs e)
    {
        Container.Dispose();
        base.OnExit(e);
    }
}

Where

Implement a data provider class, for instance like DataProvider

public class DataProvider: ObjectDataProvider
{
    private readonly IContainer _container =
        (Application.Current as App)?.Container
        // Resolves from Design Time Container
        ?? Container.Create().Using<ClockDesignTimeConfiguration>();

    public object Tag { get; set; }

    protected override void BeginQuery() => OnQueryFinished(_container.Resolve<object>(ObjectType, Tag));
}

Where ClockDesignTimeConfiguration is the desing time configuration of IoC container for view models.

Use it in XAML do bind view models like here

<Window x:Class="WpfAppNetCore.Views.MainWindow" x:ClassModifier="internal"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfAppNetCore"
        xmlns:viewModels="clr-namespace:Clock.ViewModels;assembly=Clock">
    <Window.Resources>
        <local:DataProvider x:Key="ClockViewModel" ObjectType="{x:Type viewModels:IClockViewModel}" />
    </Window.Resources>
    <Grid DataContext="{StaticResource ClockViewModel}">
        <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
            <!-- ReSharper disable once Xaml.BindingWithContextNotResolved -->
            <TextBlock Text="{Binding Date}" FontSize="64" />
            <!-- ReSharper disable once Xaml.BindingWithContextNotResolved -->
            <TextBlock Text="{Binding Time}" FontSize="64" />
            <StackPanel.Effect> <DropShadowEffect Color="Black" Direction="20" ShadowDepth="5" Opacity="0.5"/> </StackPanel.Effect>
        </StackPanel>
    </Grid>
</Window>