Lets start off creating a class that shows some info about the computer. Here is the class.
Public Class ComputerInfo
Public ReadOnly Property UserName() As String
Get
Return Environment.UserName
End Get
End Property
Public ReadOnly Property ComputerName() As String
Get
Return Environment.MachineName
End Get
End Property
Public ReadOnly Property UpTime() As Integer
Get
Return Environment.TickCount
End Get
End Property
End Class
Ok lets register the class with the form.
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WPFOneWayBindToVariable"
Title="WPFOneWayBindToVariable" Height="300" Width="300"
>
Now lets create a grid with 2 columns and 3 rows to show the class in.
Lets put the data in the grid we just created.
To get the form to update itself automatically when a value changes in the class the class has to inherit from DependencyObject. The properties values that can change must be stored in a DependencyProperty. In this class I want the UpTime property to update itself every second with a timer.
Imports System.Windows.Threading
Public Class ComputerInfo
Inherits DependencyObject
Public Shared TickCountProperty As DependencyProperty = DependencyProperty.Register("UpTime", GetType(Integer), GetType(ComputerInfo))
Public Sub New()
Dim dt As New DispatcherTimer
AddHandler dt.Tick, AddressOf TimerTick
With dt
.Interval = TimeSpan.FromSeconds(1)
.Start()
End With
End Sub
Public ReadOnly Property UserName() As String
Get
Return Environment.UserName
End Get
End Property
Public ReadOnly Property ComputerName() As String
Get
Return Environment.MachineName
End Get
End Property
Public ReadOnly Property UpTime() As Integer
Get
Return GetValue(TickCountProperty)
End Get
End Property
Public Sub TimerTick(ByVal sender As Object, ByVal e As EventArgs)
SetValue(TickCountProperty, Environment.TickCount)
End Sub
End Class
Here is the windows complete XAML
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WPFOneWayBindToVariable"
Title="WPFOneWayBindToVariable" Height="300" Width="300"
>
No comments:
Post a Comment