将TextBlock绑定到数据或只设置文本

时间:2013-07-25 20:12:44

标签: c# wpf data-binding

我正在实现一个需要每秒多次更新许多TextBlocks的实时系统。具体来说,我需要更新TextBlock.Text和TextBlock.Foreground。

一般情况下,将TextBlock.Text和TextBlock.Foreground属性绑定到数据会更好(更快,更有效),或者只是调度到UI线程并手动设置这些属性更有效吗?

1 个答案:

答案 0 :(得分: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));
    }
}