IValueConverter does not work for SolidColorBrush

I have a progress bar that I want to change color based on a boolean value; true is green and false is red. I have code that seems to work (it returns the correct value when I bind it to a text field), but not when it is a color property of the progress bar. The converter is defined like this (in App.xaml.cs, since I want to access it anywhere):

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; } } 

Then I add the following to App.xaml (so it could be a global resource):

 <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> <SolidColorBrush Color="{Binding isNeeded, Converter={StaticResource progressBarConverter}}" /> </ProgressBar.Foreground> <ProgressBar.Background> <SolidColorBrush Color="{StaticResource PhoneBorderColor}"/> </ProgressBar.Background> </ProgressBar> </StackPanel> </DataTemplate> </Application.Resources> 

I added the following to MainPage.xaml:

 <Grid x:Name="LayoutRoot" Background="Transparent"> <ListBox x:Name="listBox" ItemTemplate="{StaticResource ItemTemplate}"/> </Grid> 

And then in MainPage.xaml.cs I define a class to store data and bind it to a listBox:

 namespace PhoneApp1 { public class TestClass { public bool isNeeded { get; set; } public string name { get; set; } } public partial class MainPage : PhoneApplicationPage { // Constructor public MainPage() { InitializeComponent(); var list = new LinkedList<TestClass>(); list.AddFirst( new TestClass { isNeeded = true, name = "should be green" }); list.AddFirst( new TestClass { isNeeded = false, name = "should be red" }); listBox.ItemsSource = list; } } } 

I have attached a minimal working example so that it can be simply built and tested. The output image is here:

enter image description here

It returns values ​​from the converter for the text field, but not a progress bar. When I run the debugger, it doesn't even call it.

Thanks for any help!

+6
source share
1 answer

Try changing your converter to return SolidColorBrush and then bind directly to the ProgressBars Foreground property.

+3
source

Source: https://habr.com/ru/post/905727/


All Articles