我已经使用WPF / XAML编写了一个简单的UI,并成功地使用了iNotifyPropertyChanged方法来更新一些值。。。
XAML:
<TextBlock Grid.Column="3" Grid.Row="1" Margin=" 1" Text="{Binding DeviceType, StringFormat=0, Mode=OneWay}" FontFamily="Nexa"/>
<TextBlock Grid.Column="3" Grid.Row="2" Margin= "1" Text="{Binding DeviceSerial, StringFormat=0, Mode=OneWay}" FontFamily="Nexa"/>
<TextBlock Grid.Column="3" Grid.Row="3" Margin=" 1" Text="{Binding DeviceName, StringFormat=0, Mode=OneWay}" FontFamily="Nexa"/>
<TextBlock Grid.Column="3" Grid.Row="4" Margin=" 1" Text="{Binding DeviceBatteryLevel, StringFormat=0, Mode=OneWay}" FontFamily="Nexa"/>
背后的代码:
public partial class MainWindow : Window
{
public InstrumentViewModel Instrument = new InstrumentViewModel();
public MainWindow()
{
InitializeComponent();
this.WindowStartupLocation = WindowStartupLocation.CenterScreen;
DataContext = Instrument;
var collection = new PortableDeviceCollection();
collection.Refresh();
foreach (var device in collection)
{
device.Connect();
if (device.DeviceModel == "Instrument Test Platform")
{
Instrument.DeviceType = device.DeviceModel;
Instrument.DeviceSerial = device.DeviceSerialNumber;
Instrument.DeviceName = device.FriendlyName;
}
}
}
}
这绝对好用。但是,我想使用计时器来轮询设备。当我执行此操作并尝试使用Timer事件中的INotifyPropertyChanged方法时,正在更新我的Instrument类中的属性-但未设置XAML绑定。
我正在尝试:
public partial class MainWindow : Window
{
public InstrumentViewModel Instrument = new InstrumentViewModel();
public MainWindow()
{
InitializeComponent();
this.WindowStartupLocation = WindowStartupLocation.CenterScreen;
DataContext = Instrument;
Timer intervalTimer = new Timer(5000);
intervalTimer.Enabled = true;
intervalTimer.AutoReset = true;
intervalTimer.Elapsed += OnTimedEvent;
}
private static void OnTimedEvent(Object source, System.Timers.ElapsedEventArgs e)
{
InstrumentViewModel Instrument = new InstrumentViewModel();
var collection = new PortableDeviceCollection();
collection.Refresh();
foreach (var device in collection)
{
device.Connect();
if (device.DeviceModel == "Instrument Test Platform")
{
Instrument.DeviceType = device.DeviceModel;
Instrument.DeviceSerial = device.DeviceSerialNumber;
Instrument.DeviceName = device.FriendlyName;
}
}
}
}
我想我这里缺少一些基本知识,但是我假设位于MainWindow类中的OnTimedEvent方法仍将能够从XAML代码访问DataBinding。
这与我设置的位置有关吗
DataContext = Instrument;
吗?
任何建议表示赞赏。
谢谢。