C# 用户控件未使用 DispatcherTimer Tick 事件更新
C# usercontrol not updating with DispatcherTimer Tick Event
我在使用 DispatcherTimer 发出信号以从某些温度传感器获取新数据时在主页中更新 UserControl 时遇到问题。
Sensors.xaml.cs
public sealed partial class Sensors : UserControl
{
public Sensors()
{
this.InitializeComponent();
}
public string Sensorlbl
{
get { return (string)GetValue(SensorlblProperty); }
set { SetValue(SensorlblProperty, value); }
}
// Using a DependencyProperty as the backing store for Sensorlbl. This enables animation, styling, binding, etc...
public static readonly DependencyProperty SensorlblProperty =
DependencyProperty.Register("SensorLbl", typeof(string), typeof(Sensors), null);
Sensors.xaml
<Grid>
<TextBlock Name="SensorLbl" HorizontalAlignment="Center" VerticalAlignment="Top" Margin="0,5,0,0" Text="{Binding Sensorlbl, ElementName=userControl, Mode=TwoWay}"/>
</Grid>
MainPage.xaml.cs
public MainPage()
{
tempTimer = new DispatcherTimer();
tempTimer.Tick += GetTemp;
tempTimer.Interval = TimeSpan.FromMilliseconds(1000);
tempTimer.Start();
Sensor1.Sensorlbl = "test";
}
public void GetTemp(object sender, object e)
{
Sensor1.Sensorlbl = "Test Working";
Debug.WriteLine(Sensor1.Sensorlbl);
}
MainPage.xaml
<local:Sensors x:Name="Sensor1" Margin="0,0,0,0" Width="107" Height="155" />
对于上面的示例,我只是用它来尝试证明更新 MainPage 中使用的 UserControl。当我 运行 程序时,我得到 "Test Working" 的输出,但屏幕仍然只显示 "test".
感谢任何建议。
DependencyProperty 的注册区分大小写。它必须与 属性 的名称精确匹配。在您的情况下,您不匹配:SensorLbl 与 Sensorlbl。
我在使用 DispatcherTimer 发出信号以从某些温度传感器获取新数据时在主页中更新 UserControl 时遇到问题。
Sensors.xaml.cs
public sealed partial class Sensors : UserControl
{
public Sensors()
{
this.InitializeComponent();
}
public string Sensorlbl
{
get { return (string)GetValue(SensorlblProperty); }
set { SetValue(SensorlblProperty, value); }
}
// Using a DependencyProperty as the backing store for Sensorlbl. This enables animation, styling, binding, etc...
public static readonly DependencyProperty SensorlblProperty =
DependencyProperty.Register("SensorLbl", typeof(string), typeof(Sensors), null);
Sensors.xaml
<Grid>
<TextBlock Name="SensorLbl" HorizontalAlignment="Center" VerticalAlignment="Top" Margin="0,5,0,0" Text="{Binding Sensorlbl, ElementName=userControl, Mode=TwoWay}"/>
</Grid>
MainPage.xaml.cs
public MainPage()
{
tempTimer = new DispatcherTimer();
tempTimer.Tick += GetTemp;
tempTimer.Interval = TimeSpan.FromMilliseconds(1000);
tempTimer.Start();
Sensor1.Sensorlbl = "test";
}
public void GetTemp(object sender, object e)
{
Sensor1.Sensorlbl = "Test Working";
Debug.WriteLine(Sensor1.Sensorlbl);
}
MainPage.xaml
<local:Sensors x:Name="Sensor1" Margin="0,0,0,0" Width="107" Height="155" />
对于上面的示例,我只是用它来尝试证明更新 MainPage 中使用的 UserControl。当我 运行 程序时,我得到 "Test Working" 的输出,但屏幕仍然只显示 "test".
感谢任何建议。
DependencyProperty 的注册区分大小写。它必须与 属性 的名称精确匹配。在您的情况下,您不匹配:SensorLbl 与 Sensorlbl。