我想将线的两个点绑定到ScatterViewItems内部的两个椭圆。 目前,我能够绑定到ActualCenter.X和.Y的ScatterViewItem,它可以工作,但因为椭圆不是该ScatterViewItem中的唯一元素(也有一个标签),它是偏离中心的,使得线的端点不是椭圆的中心。如何将一个属性绑定到另一个属性,并按特定数量进行偏移?
Ellipse没有ActualCenter属性。
我想知道我是否能够通过固定的金额抵消属性绑定,或者是否有其他类型的绑定可以使用,以便我可以在容器类中计算出正确的椭圆中心(对于ellipse,label和scatterviewitem),并返回它作为绑定的来源。
下面是我设置绑定的代码。 this.avatar
是指Line
形状。 node_one
和node_two
是容器对象,其中包含ScatterViewItem
。 Node
类还包含Ellipse
,我基本上将其作为源的中心,但我很满意当前源的一个简单偏移量。
BindingOperations.SetBinding(this.avatar, Line.X1Property, new Binding
{
Source = node_one.getScatterViewItem(),
Path = new PropertyPath("ActualCenter.X")
});
BindingOperations.SetBinding(this.avatar, Line.Y1Property, new Binding
{
Source = node_one.GetNodeCenterY(),
Path = new PropertyPath("GetNodeCenterY()")
});
// Bind line.(X2,Y2) to destination.ActualCenter
BindingOperations.SetBinding(this.avatar, Line.X2Property, new Binding
{
Source = node_two.getScatterViewItem(),
Path = new PropertyPath("ActualCenter.X")
});
BindingOperations.SetBinding(this.avatar, Line.Y2Property, new Binding
{
Source = node_two.GetNodeCenterY(),
Path = new PropertyPath("GetNodeCenterY()")
});
我试图设置为Source
为node_one
和Path
为new PropertyPath("getOffsetCenter()")
返回了一倍,但没有奏效。它没有抱怨,但它没有工作:)任何提示赞赏:)
编辑,尝试使用的IValueConverter:
[ValueConversion(typeof(Double), typeof(Double))]
public class OffsetValues : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
DateTime date = (DateTime)value;
Double y = (Double)value;
Double offset = (Double)parameter;
return y + offset;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
Double dblValue = (Double)value;
Double offset = (Double)parameter;
Double resultDblValue = dblValue - offset;
return resultDblValue;
}
}
上面添加一个新的类,但我如何将它附加到我的绑定源 - MSDN中的示例具有基于XAML的实现,但我的程序都是。
感谢您的回复Fischermaen。 MSDN网站上的实现是基于XAML的 - 在C#中等价于什么?我也试着用属性“offsetValue”创建一个单独的类,其中构造函数使用提供的参数初始化offsetValue。我使用这个类的实例作为源,并使用“offsetValue”作为Path,但没有工作;我认为任何对象都可以用作Source,但只有DependencyProperties作为目标? – ataulm
nvm,我发现它的意思是作为内联绑定的“Converter =”值。 – ataulm
@ timberwo7ves:您也可以在源代码中添加值转换器。 'Binding'类也有一个Converter属性。几乎所有的东西都可以在Xaml中设置,也可以在后面的代码中设置。 – Fischermaen