首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> 關於.NET

WPF Bug 清單 (12):自訂 Attached Property 的 Binding Path 省略導致執行時解析錯誤

     編輯:關於.NET

現象

XAML 標記延伸 {Binding PropertyName} 省略 Path= 在標準 CLR 屬性正常運作,但針對自訂 Attached Property 會拋出執行時解析錯誤。

重現代碼

<Window x:Class="BindingPathBug.DemoWindow"
        xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:BindingPathBug"
        Title="{Binding (ToolTipService.ToolTip), ElementName=button}"
        Height="300" Width="300">
  <Button x:Name="button"
          ToolTipService.ToolTip="Tooltip"
          Content="{Binding (local:ContentService.Content), ElementName=button}"
          local:ContentService.Content="Button Content"/>
</Window>
  • 第一處綁定 ToolTipService.ToolTip(內建 Attached Property)正常。
  • 第二處綁定 local:ContentService.Content(自訂 Attached Property)失敗。

正確寫法

Content="{Binding Path=(local:ContentService.Content), ElementName=button}"

必須顯式指定 Path=。

原因

Binding 標記延伸解析器在處理「屬性名稱直接作為字串」時,對內建與自訂 Attached Property 的型別推斷邏輯不一致,導致自訂屬性無法正確解析為 Path。屬於 Binding Markup Extension 解析器缺陷。

修正版本

.NET 4.0 Beta 2 已修復(XAML 解析器重寫)。

最佳實務

習慣完整寫法 {Binding Path=PropertyName},特別是針對 Attached Property、索引子、巢狀路徑,可避免此類難以診斷的執行時錯誤。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved