如何使用转换器更改datatemplated wpf列表框的字体颜色?

时间:2012-06-27 20:08:26

标签: wpf datatemplate ivalueconverter

我有一个列表框使用的DataTemplate:

<local:BooleanToFontColorConverter x:Key="boolToFontColor" />
<DataTemplate x:Key="ListBox_DataTemplateSpeakStatus">
    <Label Width="Auto">
            <TextBlock Name="MY_TextBlock" Text="Hello!" Foreground="{Binding Path=MY_COLOR, Converter={StaticResource boolToFontColor}}" />
    </Label>
</DataTemplate>

MY_COLOR是以下代码:

    public class Packet_Class : INotifyPropertyChanged
    {
        private bool _my_color = false;
        public bool MY_COLOR { get { return _my_color; } 
                                       set { _my_color = value; RaisePropertyChanged("MY_COLOR"); } }
    }

然后在适当的时候设置属性,我认为会激活RaisePropertyChanged函数

    myPacketClass.MY_COLOR = true;

而boolToFontColor正在“尝试”使用此位:

    public class BooleanToFontColorConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter,
                  CultureInfo culture)
    {
        if (value is Boolean)
        {
            return ((bool)value) ? new SolidColorBrush(Colors.Red) : new SolidColorBrush(Colors.Black);
        }

        return new SolidColorBrush(Colors.Black);
    }

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

当我将MY_COLOR的值从true更改为false时,反之亦然,我发现在运行时期间我的文本前景色没有可见的变化。有人能就我出错的地方提出建议吗?非常感谢并提前感谢你。

编辑:

尝试提供更清晰的一些其他信息。我在ListBox中使用我的DataTemplate,如下所示:

<ListBox x:Name="MyUserList" ItemTemplate="{StaticResource ListBox_DataTemplateSpeakStatus}"  SelectionMode="Extended" />

在我的WPF Window元素中,我将本地命名空间设置为我的mainwindow.xaml.cs封装在的命名空间:

xmlns:local ="clr-namespace:My_NameSpace"

1 个答案:

答案 0 :(得分:3)

RaisePropertyChanged方法应该在界面中引发PropertyChanged事件定义,如下所示:

public event PropertyChangedEventHandler PropertyChanged;
        protected void RaisePropertyChanged (string propertyName)
        {
            if (this.PropertyChanged != null)
                this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }

转换器:

public class BooleanToFontColorConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter,
              CultureInfo culture)
    {
        if (value is Boolean)
        {
            return ((bool)value) ? new SolidColorBrush(Colors.Red) : new SolidColorBrush(Colors.Black);
        }

        return new SolidColorBrush(Colors.Black);
    }

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

您必须使用SolidColorBrush才能使其正常运行。

它适用于我的环境,如果您遇到任何麻烦,请告诉我。

相关问题