I have a progress bar that I want to change color depending on a boolean value; true is green and false is red. I have code that seems like it should work (it returns the correct value when I bind it to a textbox) but not when it's the color property of the progress bar. The converter is defined as 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;
}
}
I then add the following to the App.xaml (so it can 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 to display them:
<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 hold the data and bind it to the 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've attached a minimal working example so it can just be built and tested. An image of the output is here:
It returns the values from the converter for the textbox but not the progress bar. When I run the debugger, it doesn't even call it.
Thanks for any help!
Try to modify your converter to return a SolidColorBrush
and then bind directly to your ProgressBars
Foreground property.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With