如何将附加属性作为数据绑定的源进行引用?

5
下面是我代码的缩略版样例。
<Grid>

<Polygon
  Name="ply" Grid.Column="2" Grid.Row="0" Grid.RowSpan="3"
  Fill="Orange" Stroke="Orange" Points="0,1 1,3 2,2 2,0 0,0"
/>

<Line
  Grid.Column=    "{Binding ElementName=ply, Path=Grid.Column, Mode=OneWay}"
  Grid.Row=       "{Binding ElementName=ply, Path=Grid.Row, Mode=OneWay}"
  Grid.ColumnSpan="{Binding ElementName=ply, Path=Grid.ColumnSpan, Mode=OneWay}"
  Grid.RowSpan=   "{Binding ElementName=ply, Path=Grid.RowSpan, Mode=OneWay}"
  X1="0" Y1="0" X2="1" Y2="1"
/>

</Grid>

代码编译没有任何错误或警告,但当我运行应用程序时,在输出窗口中出现以下内容:
System.Windows.Data Error: 39 : BindingExpression path error:
'Grid' property not found on 'object' ''Polygon' (Name='ply')'.
BindingExpression:Path=Grid.Column; DataItem='Polygon' (Name='ply');
target element is 'Line' (Name=''); target property is 'Column' (type 'Int32')

System.Windows.Data Error: 39 : BindingExpression path error:
'Grid' property not found on 'object' ''Polygon' (Name='ply')'.
BindingExpression:Path=Grid.Row; DataItem='Polygon' (Name='ply');
target element is 'Line' (Name=''); target property is 'Row' (type 'Int32')

System.Windows.Data Error: 39 : BindingExpression path error:
'Grid' property not found on 'object' ''Polygon' (Name='ply')'.
BindingExpression:Path=Grid.ColumnSpan; DataItem='Polygon' (Name='ply');
target element is 'Line' (Name=''); target property is 'ColumnSpan' (type 'Int32')

System.Windows.Data Error: 39 : BindingExpression path error:
'Grid' property not found on 'object' ''Polygon' (Name='ply')'.
BindingExpression:Path=Grid.RowSpan; DataItem='Polygon' (Name='ply');
target element is 'Line' (Name=''); target property is 'RowSpan' (type 'Int32')

我显然没有做对,所以我的问题是:
如何正确引用数据绑定中源元素上的附加属性"Grid.Whatever"? 我是否需要在代码后台执行绑定,或者使用不同语法的XAML绑定就足够了?

1个回答

7
你可能会笑,但其实只是语法稍有不同。你只需要在属性名称周围加上括号(第一次我做这件事时花了很长时间才弄明白):
<Line
  Grid.Column=    "{Binding ElementName=ply, Path=(Grid.Column), Mode=OneWay}"
  Grid.Row=       "{Binding ElementName=ply, Path=(Grid.Row), Mode=OneWay}"
  Grid.ColumnSpan="{Binding ElementName=ply, Path=(Grid.ColumnSpan), Mode=OneWay}"
  Grid.RowSpan=   "{Binding ElementName=ply, Path=(Grid.RowSpan), Mode=OneWay}"
  X1="0" Y1="0" X2="1" Y2="1"
/>

希望这能帮到您, 安德森

2
运行得非常完美。是啊,我笑了。当一些如此简单和愚蠢的东西阻碍你一个小时的进展时,这真是令人沮丧。 - Giffyguy
1
很高兴能够帮忙并逗你一笑。 - Anderson Imes
2
@Giffyguy 只需要一个小时吗? - Dr. Andrew Burnett-Thompson

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接