WPF双重约束
问题 我创建了一串椭圆,我希望它们的填充笔刷不透明度根据滑块值进行更改。我将滑块绑定到一个属性,并通过转换器将椭圆的FillProperty绑定到相同的属性。当我更新滑块时,椭圆不会改变。但是,当我重新创建它们时,它们会发生变化。WPF双重约束
我觉得Ellipse绑定没有看到我通过其他绑定进行的更改,因此不会更新。我不知道要设置什么标志使其将级联我正在对属性进行的更改,或者是否需要将属性包装在某种花哨的对象中。
希望有任何帮助。
技术细节 我有一个类:声明一(公共,自动)称为BubbleOpacity
财产(窗口)。在某个时候,我创建一个滑块并将其绑定(双向)到我的属性。
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
到目前为止好。然后我创建了几个省略号。其中一个椭圆可能看起来像这样:
var ellipse = new Ellipse {*}我设置了Width,Height,Margin,Stroke ...等等 }; (新的SolidColorBrush(Colors.LightGoldenrodYellow))});
BrushOpacityConverter
类仅根据传递的不透明度值创建新画笔。它看起来像这样,如果你必须知道。
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;
}
如果我在Convert方法上设置了断点,我发现当我更新滑块时它不会被调用。它在我重新创建椭圆时确实会被调用(正确)。
问题是,当您更改BubbleOpacity
属性时,您不会通知任何人您已更改它。
要修复此问题,您可以实施INotifyPropertyChanged
界面,并在BubbleOpacity属性更改时引发PropertyChanged事件。
另一种选择是将BubbleOpacity
财产申报作为一个依赖属性,像这样:
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));
我宁愿第二个选项(因为这个属性的DependencyObject内声明的)。
非常感谢,作品广告。如果想要用google找到这些东西,这将会花费很多时间,所以再次感谢您输入解决方案。 =) – Gleno 2011-01-27 16:45:37