我正在实现一个需要每秒多次更新许多 TextBlock 的实时系统。具体来说,我需要更新 TextBlock.Text 和 TextBlock.Foreground。
一般来说,将 TextBlock.Text 和 TextBlock.Foreground 属性绑定到数据会更好(更快更高效),还是直接分派到 UI 线程并手动设置这些属性更有效?
我正在实现一个需要每秒多次更新许多 TextBlock 的实时系统。具体来说,我需要更新 TextBlock.Text 和 TextBlock.Foreground。
一般来说,将 TextBlock.Text 和 TextBlock.Foreground 属性绑定到数据会更好(更快更高效),还是直接分派到 UI 线程并手动设置这些属性更有效?
您可能需要考虑使用转换器来更改 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));
}
}