Ravi Khambhati
Ravi Khambhati

Reputation: 743

Implement Service Layer in WPF application

I am working on WPF application and new to it so this might be a dumb question,

What I would like to do is trigger binding from my service layer. To explain better I have created an example. In this example, I would like to bind grid with logged messags(from service method) on my WPF screen.

See my comment in ServiceMethod in Service class. This is the place I would like to trigger binding.

I tried to explain with best possible way but do not hesitate if you need further clarification on this.

XAML

<Window x:Class="WpfApp1.ServiceExample"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp1"
        mc:Ignorable="d"
        Title="ServiceExample" Height="300" Width="300">
    <Window.Resources>
        <local:ServiceExampleViewModel x:Key="serviceExampleViewModel"></local:ServiceExampleViewModel>
    </Window.Resources>
    <Grid>
        <StackPanel Orientation="Vertical">
            <DataGrid ItemsSource="{Binding MessageLog,
                    Source={StaticResource serviceExampleViewModel},
                    Mode=TwoWay,
                    UpdateSourceTrigger=PropertyChanged}">
            </DataGrid>
            <Button Content="Call Service" Command="{Binding CallService,
                Mode=TwoWay, Source={StaticResource serviceExampleViewModel}}"></Button>
            <Label Content="{Binding ServiceResult, 
                    Source={StaticResource serviceExampleViewModel},
                    Mode=TwoWay,
                    UpdateSourceTrigger=PropertyChanged}"></Label>
        </StackPanel>

    </Grid>
</Window>

ServiceExample

public partial class ServiceExample : Window
{
    public ServiceExample()
    {
        InitializeComponent();
    }
}

btnClick

public class btnClick : System.Windows.Input.ICommand
{
    private Action WhatToExecute;
    private Func<bool> WhenToExecute;
    public btnClick(Action what, Func<bool> when)
    {
        WhatToExecute = what;
        WhenToExecute = when;
    }
    public void Refresh()
    {
        if (this.CanExecuteChanged != null)
        {
            CanExecuteChanged(this, EventArgs.Empty);
        }
    }
    public event EventHandler CanExecuteChanged;
    public bool CanExecute(object parameter)
    {
        return WhenToExecute();
    }
    public void Execute(object parameter)
    {
        WhatToExecute();
    }
}

ServiceExampleViewModel

class ServiceExampleViewModel : System.ComponentModel.INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    private int serviceResult;
    public int ServiceResult
    {
        get { return serviceResult; }
        set
        {
            serviceResult = value;
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("ServiceResult"));
        }
    }
    public btnClick CallService { get; set; }
    public Service ServiceObj { get; set; }
    public ServiceExampleViewModel()
    {
        ServiceObj = new Service();
        this.CallService = new btnClick(CallServiceMethod, () => { return true; });
    }

    private void CallServiceMethod()
    {
        this.ServiceResult = this.ServiceObj.ServiceMethod();
    }
}

Message

class Message
{
    public string Text { get; set; }
}

Service

class Service
{
    public List<Message> MessageLog;

    public Service()
    {
        this.MessageLog = new List<Message>();
    }

    public int ServiceMethod()
    {
        int result = 0;
        for (int counter = 0; counter < 10; ++counter)
        {
            //This is where binding should trigger
            this.MessageLog.Add(new Message() { Text = string.Format("{0}:{1}", DateTime.Now.Ticks, counter) });

            result += counter;
        }
        return result;
    }
}

Upvotes: 0

Views: 1663

Answers (1)

slugster
slugster

Reputation: 49985

In MVVM you don't have bindings from a service, not ever. The purpose of a service is to be a conduit of data, maybe with some limited business logic in it. Services can have a very short lifetime and they typically don't maintain any state.

Your bindings should be between your view and your viewmodel, to bind any other way is violating the pattern.

Upvotes: 1

Related Questions