将TextBlock绑定到数据或仅设置文本
本文关键字:置文本 数据 TextBlock 绑定 | 更新日期: 2023-09-27 18:24:54
我正在实现一个实时系统,该系统需要每秒多次更新许多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));
}
}