.net - 如何引用附加属性作为数据绑定(bind)的来源?

标签 .net wpf data-binding xaml .net-3.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')

我显然没有正确执行此操作,所以我的问题是:
如何在我的数据绑定(bind)中正确引用源元素上的附加属性“Grid.Whatever”?我是否必须改为在代码隐藏中执行绑定(bind),还是使用不同语法的 XAML 绑定(bind)就足够了?

最佳答案

你会笑,但这只是语法略有不同。您只需要在附加的属性名称周围加上括号(这让我很长时间才弄清楚我第一次这样做的时候):

<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"
/>

希望这可以帮助,
安德森

关于.net - 如何引用附加属性作为数据绑定(bind)的来源?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1408749/

相关文章:

angular - 尝试绑定(bind)到 dx-date-box 时,类型 'string | number | Date' 无法分配给类型 'Date'

c# - 'System.Data.DataRowCollection' 不包含 "Length"的定义

wpf - 谁对 WPF 依赖属性有最好的比喻?

c# - 是否可以在 XAML 中绑定(bind) Canvas 的 Children 属性?

c# - 如何将图像控件绑定(bind)到以 VarBinary 类型保存在数据库中的图像

java - JFace数据绑定(bind): Update model only if all validators succeed

.net - 无法从 VB.NET 应用程序关闭 Excel 进程

.net - 在.NET标签中插入换行符

.net - ASP.NET 延迟作业以运行异步代码?

c# - 如何捕获/观察任务抛出的未处理异常