Change border color based on boolean
I have a wihch border. I want to change its color depending on a boolean variable. I used the link here to implement the converter Boolean
to Color
.
The code looks like this:
xaml:
<Border Width="45"
Height="45" CornerRadius="5"
Background="{Binding Path=LivenessActive, Converter={StaticResource BrushColorConverter}}" />
Variable LivenessActive in the background:
public bool LivenessActive
{
get { return _livenessActive; }
set
{
_livenessActive = value;
OnPropertyChanged("LivenessActive");
}
}
If the class has inheritance for INotifyPropertyChanged
and has implemented an event OnPropertyChanged
.
BrushColorConverter.cs:
public class BrushColorConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if ((bool)value)
{
{
return new SolidColorBrush(Colors.GreenYellow);
}
}
return new SolidColorBrush(Colors.DarkGray);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
But I can't even run BrushColorConverter
. What am I doing wrong?
2nd: What if I want to use it from another window?
<Border Width="45" Height="45" CornerRadius="5"
Background="{Binding Path=LivenessActive, Converter={StaticResource BrushColorConverter},
RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type view:MyWindowName}}}" />
I used this same code and couldn't find it.
source to share
To summarize the comments, since there seems to be nothing wrong with the code above, this suggests there is an issue with the binding context for
Background="{Binding Path=LivenessActive, Converter={StaticResource BrushColorConverter}}"
You cannot link from one Window
to the other Window
. If you have 2 independent ones Window
, each of which has Border
to be launched on the same property change, you set DataContext
both windows to the same view model instance.
source to share