我有一个Slider Binded到一行的ScaleX,如下面的代码:
/* Graphics on Canvas */
Line lR = new Line();
lR.X1 = 0;
lR.Y1 = 0;
lR.X2 = 150;
lR.Y2 = 150;
lR.Stroke = new SolidColorBrush(Colors.Blue);
lR.StrokeThickness = 2;
/* declare ScaleTransformation */
ScaleTransform lRSt = new ScaleTransform();
TransformGroup lRTran = new TransformGroup();
lRTran.Children.Add(lRSt);
lR.RenderTransform = lRTran;
Binding sliderRBind1 = new Binding();
sliderRBind1.Source = sliderR;
sliderRBind1.Path = new PropertyPath("Value");
BindingOperations.SetBinding(lRSt, ScaleTransform.ScaleXProperty, sliderRBind1);
BindingOperations.SetBinding(lRSt, ScaleTransform.ScaleYProperty, sliderRBind1);
/* Slider - Slider should be placed outside the canvas to prevent being redrawn */
Slider sliderR = new Slider();
sliderR.Minimum = 1;
sliderR.Maximum = 3;
sliderR.Value = 1;
sliderR.TickPlacement = TickPlacement.BottomRight;
sliderR.TickFrequency = 0.2;
sliderR.IsSnapToTickEnabled = true;
代码工作正常。但是,如果我将ScaleTransform移动到方法,则Binding将丢失。
/* Graphics on Canvas */
Line lR = new Line();
lR.X1 = 0;
lR.Y1 = 0;
lR.X2 = 150;
lR.Y2 = 150;
lR.Stroke = new SolidColorBrush(Colors.Blue);
lR.StrokeThickness = 2;
/* declare ScaleTransformation */
ScaleTransform lRSt = new ScaleTransform();
TransformGroup lRTran = new TransformGroup();
lRTran.Children.Add(lRSt);
lR.RenderTransform = lRTran;
LineSliderR(lR);
/* Slider - Slider should be placed outside the canvas to prevent being redrawn */
Slider sliderR = new Slider();
sliderR.Minimum = 1;
sliderR.Maximum = 3;
sliderR.Value = 1;
sliderR.TickPlacement = TickPlacement.BottomRight;
sliderR.TickFrequency = 0.2;
sliderR.IsSnapToTickEnabled = true;
public void LineSliderR(Line lRSt)
{
Binding sliderRBind1 = new Binding();
sliderRBind1.Source = sliderR;
sliderRBind1.Path = new PropertyPath("Value");
BindingOperations.SetBinding(lRSt, ScaleTransform.ScaleXProperty, sliderRBind1);
BindingOperations.SetBinding(lRSt, ScaleTransform.ScaleYProperty, sliderRBind1);
}
如果调用单独的方法,为什么Binding会失败?
这两个代码对我来说是相同的。两者都包含四个相同的“事物”: 一个Line,一个ScaleTransform,一个Binding和一个Slider。
第一个代码在函数中包含所有4个“东西”。第二个代码具有来自单独函数的Binding调用。两者都编译没有错误:但是,Binding(在Line和Slider之间)在第一个代码上工作正常,但不在第二个代码上工作。我正在尝试使用第二个代码,因为我有许多Line,而且我不想重复自己。
答案 0 :(得分:2)
在第二个代码块中,在方法LineSliderR
内,lRSt是Line
类型的对象,而在第一个块中,它是ScaleTransform
类型。
如果您希望第二个块的行为与第一个块类似,则方法LineSliderR应接受ScaleTransform
'作为参数:
public void LineSliderR(ScaleTransform lRSt)