Skip to main content

First WPF App

This guide builds the smallest WPF host window: type text, click send, receive the virtual-channel echo, and show channel state.

Run the Sample

From the repository code directory:

dotnet run --project samples/Zeus.Samples.Wpf.QuickStart

The window should show Open, send PING, and display the echo.

Required Packages

dotnet add package Zeus.Communications
dotnet add package Zeus.Presentation.Wpf

Project file:

<TargetFramework>net8.0-windows</TargetFramework>
<UseWPF>true</UseWPF>

XAML

<Window x:Class="MyApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Zeus WPF QuickStart"
Height="260"
Width="520">
<Grid Margin="16">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="80" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>

<TextBlock Grid.Row="0" Grid.Column="0" Text="Send" />
<TextBox x:Name="InputBox" Grid.Row="0" Grid.Column="1" Text="PING" />
<Button x:Name="SendButton" Grid.Row="1" Grid.Column="1" Content="Send" Click="OnSendClick" />
<TextBlock Grid.Row="2" Grid.Column="0" Text="State" />
<TextBlock x:Name="StateText" Grid.Row="2" Grid.Column="1" />
<TextBlock Grid.Row="3" Grid.Column="0" Text="Echo" />
<TextBlock x:Name="EchoText" Grid.Row="3" Grid.Column="1" />
</Grid>
</Window>

Code-Behind

using System.Text;
using System.Windows;
using Zeus;

public partial class MainWindow : Window
{
private readonly IChannel _meter;

public MainWindow()
{
InitializeComponent();

var attachment = this.AttachZeus(builder => builder.AddVirtualChannel("meter"));
_meter = attachment.Host.Channels.Get("meter");
_meter.BindState(StateText);
_meter.BindTo(EchoText);
_meter.BindEnabled(SendButton);
}

private async void OnSendClick(object sender, RoutedEventArgs e)
{
await _meter.WriteAsync(Encoding.UTF8.GetBytes(InputBox.Text));
}
}

Why No Manual Dispatcher.Invoke

Channel callbacks may come from IO threads. WPF controls must be updated on the Dispatcher thread. BindTo, BindState, and BindEnabled wrap that Dispatcher handoff.

If you prefer data binding, use:

DataContext = _meter.AsBindingSource(this);

Common binding-source properties include LastText, LastHex, StateText, and ReceivedCount.

Next: WPF Adapter or Serial Port.