【发布时间】:2014-08-06 22:34:30
【问题描述】:
我目前正在学习 WPF、DataContexts 和 DataBinding。我的目标是有一个任务栏任务(使用 NotifyIconWpf),它有一个运行后台的连续线程来监控网络。
我已经设法将一个 UI 元素(如屏幕截图所示)绑定到 ProgramClock 类,但它不会在 ProgramClock 更改时更新,很可能是因为 INotifyPropertyChanged 参数中的某些内容有误。
我发现的最接近的类似问题是UI not being updated INotifyPropertyChanged,但是我无法弄清楚要更改 XAML 中的 DataPath 的内容,或者如何使 INotifyPropertyChanged 正常工作。
请注意,BackgroundWorker 线程成功更新了 App 的静态 ProgramClock(使用单独的 WinForm 检查)并且该时间最初加载到 WPF 中,因此可能是 PropertyChanged 没有被正确调用。 p>
程序时钟
public class ProgramClock : INotifyPropertyChanged
{
private DateTime _myTime;
public event PropertyChangedEventHandler PropertyChanged;
private ClockController clockController;
public ProgramClock()
{
this._myTime = DateTime.Now;
clockController = new ClockController();
MessageBox.Show("created new clock");
}
public DateTime MyTime
{
get
{
return this._myTime;
}
set
{
if (_myTime == value) return;
_myTime = value;
//System.Windows.Forms.MessageBox.Show(PropertyChanged.ToString());
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(_myTime.ToString()));
}
}
public string MyTimeString
{
get { return this._myTime.ToString(); }
}
public void UpdateTime()
{
this.MyTime = DateTime.Now;
}
}
泡泡CS
public partial class InfoBubble : System.Windows.Controls.UserControl
{
public InfoBubble()
{
InitializeComponent();
this.DataContext = App.ClockBindingContainer;
}
}
冒泡 XAML
<UserControl x:Class="FileWatcher.Controls.InfoBubble"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008">
<Border
Background="White"
BorderBrush="Orange"
BorderThickness="2"
CornerRadius="4"
Opacity="1"
Width="160"
Height="40">
<TextBlock
Text="{Binding Path=MyTimeString}"
HorizontalAlignment="Center"
VerticalAlignment="Center" />
</Border>
</UserControl>
主应用
public partial class App : System.Windows.Application
{
private TaskbarIcon tb;
private ResourceDictionary _myResourceDictionary;
public static ProgramClock _programClock = new ProgramClock();
private void Application_Startup(object sender, StartupEventArgs e)
{
NotifIconStarter();
}
public static ProgramClock ClockBindingContainer
{
get { return _programClock; }
}
}
【问题讨论】:
标签: c# wpf xaml datacontext