2017-06-07 63 views
0

我在使用DispatcherTimer發送信號以獲取來自某些溫度傳感器的新數據時,在主頁面中有UserControl更新的問題。C#usercontrol不能用DispatcherTimer更新Tick事件

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。當我運行程序時,我得到「測試工作」的輸出,但屏幕仍然只顯示「測試」。

感謝您的任何建議。

+0

我認爲在DependencyProperty定義中有一個錯字:SensorLbl vs Sensorlbl。 –

+0

對不起,這是我第一次使用c#(或任何不是基於工業機器人的編程)。你是什​​麼意思,我沒有顯示Sensor1.Sensorlbl的實現?我上面發佈的代碼是我在做這個測試時運行的代碼。應該有其他參數MainPage.xaml? –

+0

是的,這是問題。我現在覺得沒有抓住這一點很愚蠢。謝謝 –

回答

0

DependencyProperty的註冊區分大小寫。它必須精確匹配財產的名稱。在你的情況下,你有一個不匹配:SensorLbl VS Sensorlbl。

+0

再次感謝您的幫助。 –