2013-07-25 34 views
0

我正在實現一個需要每秒更新多次TextBlocks的實時系統。具體而言,我需要更新TextBlock.Text和TextBlock.Foreground。將TextBlock綁定到數據或只設置文本

一般來說,將TextBlock.Text和TextBlock.Foreground屬性綁定到數據會更好(更快,更高效),還是更有效率地分發到UI線程並手動設置這些屬性?

+0

有沒有這樣的事情'TextBlock.Color'。並使用DataBinding。總是。無論。 –

+1

只需使用探查器找出... –

+0

我編輯了這個問題。我的意思是TextBlock.Foreground。 –

回答

1

您可能需要考慮使用轉換器來改變TextBlock的前景色。以下是轉換器類可能看起來像基於某些文本的位置,我們更改顏色。

public class ForegroundColorConverter: IValueConverter 
{ 
    public object Convert(object value, Type targetType, object parameter, string language) 
    { 
     string sValue = (string)value; 
     SolidColorBrush pBrush = new SolidColorBrush(Colors.White); 
     if (sValue.ToLower() == "red") pBrush = new SolidColorBrush(Colors.Red); 
     return pBrush; 
    } 

    public object ConvertBack(object value, Type targetType, object parameter, string language) 
    { 
     throw new NotImplementedException(); 
    } 
} 

您需要將資源添加到您的用戶控件或頁面。

<Page.Resources> 
    <local:ForegroundColorConverter x:Name="ColorConverter"/> 
</Page.Resources> 

你的texblock看起來像這樣。

<TextBlock x:Name="lblText" Text="{Binding Text}" Foreground="{Binding TextColorName, Converter={StaticResource ColorConverter}}"/> 

幾乎忘了你將要綁定的類。

public class TextBlockInfo : INotifyPropertyChanged 
{ 
    //member variables 
    private string m_sText = ""; 
    private string m_sTextColorName = ""; 

    //construction 
    public TextBlockInfo() { } 
    public TextBlockInfo(string sText, string sTextColorName) 
    { 
     m_sText = sText; 
     m_sTextColorName = sTextColorName; 
    } 

    //events 
    public event PropertyChangedEventHandler PropertyChanged; 

    //properties 
    public string Text { get { return m_sText; } set { m_sText = value; this.NotifyPropertyChanged("Text"); } } 
    public string TextColorName { get { return m_sTextColorName; } set { m_sTextColorName = value; this.NotifyPropertyChanged("TextColorName"); } } 

    //methods 
    private void NotifyPropertyChanged(string sName) 
    { 
     if (this.PropertyChanged != null) this.PropertyChanged(this, new PropertyChangedEventArgs(sName)); 
    } 
}