【发布时间】:2012-06-18 14:56:43
【问题描述】:
使用 WPF 和 VB.net,我想用当前日期和时间更新文本块中的文本框。我使用了一个计时器,它似乎正在触发,并将对象属性设置为“现在”。 我正在使用 iNotifyPropertyChanged。
我得到的只是一个没有数据的空文本框。你能帮我吗?也许我的上下文已经关闭了?
XAML
<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<TextBlock DataContext="oTime">
<TextBox x:Name="myTextBox"
Width="200" Height="50" Foreground="Black"
Text="{Binding Path=oTime.TimeUpdate}"></TextBox>
</TextBlock>
</Grid>
</Window>
VB 代码
Imports System.ComponentModel
Imports System.Windows.Threading
Class MainWindow
Public oTime As TimeUpdate = New TimeUpdate
Private dpTimer As DispatcherTimer
Private Sub TextBlock_SourceUpdated(ByVal sender As System.Object, ByVal e As System.Windows.Data.DataTransferEventArgs)
End Sub
Private Sub MainWindow_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded
dpTimer = New DispatcherTimer
dpTimer.Interval = TimeSpan.FromMilliseconds(1000)
AddHandler dpTimer.Tick, AddressOf TickMe
dpTimer.Start()
End Sub
Private Sub TickMe()
oTime.TimeUpdate = Now.ToString
Debug.Print(oTime.TimeUpdate)
End Sub
End Class
Public Class TimeUpdate
Implements INotifyPropertyChanged
Private sTime As String
'Declare the Event
Public Event PropertyChanged(ByVal sender As Object, ByVal e As System.ComponentModel.PropertyChangedEventArgs) Implements System.ComponentModel.INotifyPropertyChanged.PropertyChanged
Public Property TimeUpdate() As String
Get
Return sTime
End Get
Set(ByVal value As String)
sTime = value
'Call onPropertyChanged whenever the property is updated
OnPropertyChanged("TimeUpdate")
End Set
End Property
Protected Sub OnPropertyChanged(ByVal name As String)
RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(name))
End Sub
End Class
【问题讨论】:
-
虽然它完全有效,但为什么要将 TextBox 放在 TextBlock 中? Textblock 是一个轻量级的标签,只显示一个简单的文本。只需删除文本块,没有必要。
-
我不知道为什么。我只是在尝试不同的东西来让它发挥作用。我试图更改文本块中的某些内容,但它不允许我这样做。现在不记得了。就像我说的,我现在才编写 WPF 几天,所以我得到了 OJT。这里有几个人告诉我,我应该只专注于 winforms,但我喜欢 WPF 可以做的事情。它们都不能在 WPF 中工作。
-
WPF 与 Windows 窗体有很大不同。转换可能很困难,但值得。我经常使用winforms,但现在,我不记得如何做winforms :) 我喜欢wpf。 WPF 的一个非常重要的部分是Databinding 我建议你阅读它。
-
好的,我会尝试阅读它。绑定到数据库连接和类似的东西似乎有很多。但我只是想将文本块或文本框中的数据设置为代码中的值。虽然要在 WPF 文本框中获取变量值,但要跳转很多。
-
数据绑定与数据库没有直接关系。就像您想将 TextBox.Text 属性绑定到您的 TimeUpdate 一样。但看起来,您需要更好地了解此绑定的工作原理以及 DataContext 是什么。
标签: wpf vb.net binding inotifypropertychanged