Reputation: 16959
Problem I am creating a bunch of ellipses and I want their fill-brush opacity to change according to a slider value. I bind the slider to a property and bind the ellipse's FillProperty to the same property through a converter. When I update the slider, the ellipses don't change. They do change when I recreate them, however.
I intuit that the Ellipse binding doesn't see the change that I am making through the other binding, and therefore doesn't update. I don't know what flag to set to cause it to cascade the changes that I am making to the property, or if I need to wrap the property in some kind of a fancy object.
Would appreciate any help.
Technical Details
I have a class ( :Window) that declares a (public, auto) property called BubbleOpacity
. At some point I create a slider and bind it (Two-way) to my property.
var slider = new Slider { Width = 150, Minimum = 0, Maximum = 1, Value = 0.2 };
slider.SetBinding(RangeBase.ValueProperty, new Binding("BubbleOpacity") { Source = this, Mode = BindingMode.TwoWay
So far so good. Then I create a few ellipses. One of these ellipses may look like so:
var ellipse = new Ellipse { /* I set Width, Height, Margin, Stroke... etc. }; ellipse.SetBinding(Shape.FillProperty, new Binding("BubbleOpacity") { Source = this, Converter = new BrushOpacityConverter(new SolidColorBrush(Colors.LightGoldenrodYellow)) });
The BrushOpacityConverter
class just creates a new brush, based on the passed opacity value. It looks like this, if you must know.
class BrushOpacityConverter : IValueConverter
{
private readonly Brush _brush;
public BrushOpacityConverter(Brush brush)
{
_brush = brush;
}
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var brushclone = _brush.CloneCurrentValue();
brushclone.Opacity = (double) value;
return brushclone;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return null;
}
If I set breakpoints on the Convert method, I see that it doesn't get called when I update my slider. It does get called (correctly) when I recreate the ellipses.
Upvotes: 1
Views: 3192
Reputation: 20746
The problem is that when you change the BubbleOpacity
property you don't notify anybody that you have changed it.
To fix this you can implement the INotifyPropertyChanged
interface and raise the PropertyChanged event when the BubbleOpacity property changes.
Another option is to declare the BubbleOpacity
property as a dependency property, like this:
public double BubbleOpacity {
get { return (double)GetValue(BubbleOpacityProperty); }
set { SetValue(BubbleOpacityProperty, value); }
}
public static readonly DependencyProperty BubbleOpacityProperty =
DependencyProperty.Register("BubbleOpacity", typeof(double), typeof(Window), new UIPropertyMetadata(1d));
I would prefer the second option (because this property is declared inside a DependencyObject).
Upvotes: 3