小编Tay*_*ick的帖子

IValueConverter不适用于SolidColorBrush

我有一个进度条,我想根据布尔值改变颜色; true为绿色,false为红色.我有代码似乎应该工作(它将它绑定到文本框时返回正确的值)但不是当它是进度条的颜色属性时.转换器定义为此(在App.xaml.cs中,因为我想在任何地方访问它):

public class ProgressBarConverter : System.Windows.Data.IValueConverter
{
    public object Convert(
        object o, 
        Type type, 
        object parameter, 
        System.Globalization.CultureInfo culture)
    {
        if (o == null)
            return null;
        else
            //return (bool)o ? new SolidColorBrush(Colors.Red) : 
            //                 new SolidColorBrush(Colors.Green);
            return (bool)o ? Colors.Red : Colors.Green;
    }

    public object ConvertBack(
        object o, 
        Type type, 
        object parameter, 
        System.Globalization.CultureInfo culture)
    {
        return null;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后我将以下内容添加到App.xaml(因此它可以是全局资源):

<Application.Resources>
    <local:ProgressBarConverter x:Key="progressBarConverter" />
    <DataTemplate x:Key="ItemTemplate">
        <StackPanel>
            <TextBlock Text="{Binding name}" Width="280" />
            <TextBlock Text="{Binding isNeeded, 
                          Converter={StaticResource progressBarConverter}}" />
            <ProgressBar>
                <ProgressBar.Foreground> …
Run Code Online (Sandbox Code Playgroud)

data-binding silverlight ivalueconverter windows-phone-7

6
推荐指数
1
解决办法
1599
查看次数