共用方式為


如何在 XAML 設計工具中繫結資料

在 XAML 設計工具中,您可以使用畫板和 [屬性] 視窗,設定資料繫結屬性。 本主題中的範例示範如何將資料繫結至控制項。 具體來說,此程序顯示如何建立具有名為 ItemCount 之 DependencyProperty 的簡單購物車類別,然後將 ItemCount 屬性繫結至 TextBlock 控制項的 [文字] 屬性。

若要建立類別以做為資料來源

  1. 在 [空白應用程式] 樣板中建立 C# 或 Visual Basic 專案。

  2. 開啟 MainPage.xaml.cs (或 MainPage.xaml.vb) 並加入下列程式碼。 在 C# 中,加入 projectName 命名空間中的程式碼 (在檔案中最後一個右括號之前)。 在 Visual Basic 中,只需加入新類別。

    public class ShoppingCart : DependencyObject
    {
        public int ItemCount
        {
            get { return (int)GetValue(ItemCountProperty); }
            set { SetValue(ItemCountProperty, value); }
        }
    
        public static readonly DependencyProperty ItemCountProperty =
             DependencyProperty.Register("ItemCount", typeof(int),
             typeof(ShoppingCart), new PropertyMetadata(0));
    }
    
    Public Class ShoppingCart
        Inherits DependencyObject
    
        Public Shared ReadOnly ItemCountProperty As DependencyProperty = DependencyProperty.Register(
            "ItemCount", GetType(Integer), GetType(ShoppingCart), New PropertyMetadata(0))
        Public Property ItemCount As Integer
            Get
                ItemCount = CType(GetValue(ItemCountProperty), Integer)
            End Get
            Set(value As Integer)
                SetValue(ItemCountProperty, value)
            End Set
        End Property
    End Class
    

    此程式碼會使用 PropertyMetadata 物件,將值 0 設定為預設項目計數。

    提示

    在 Visual Studio 中,您可以在 ShoppingCart 類別內輸入 propdp,然後按 TAB 鍵,以加入相依性屬性的 Stub 程式碼。

  3. 按一下 [建置] > [建置方案]。

若要將 ItemCount 屬性繫結至 TextBlock 控制項

  1. 以滑鼠右鍵按一下 MainPage.xaml,然後按一下 [檢視設計工具]。

  2. 在 [文件大綱] 視窗中,選取根 Grid 面板,它會在視窗中顯示為 [Grid]

  3. 選取 Grid 後,按一下 [屬性] 視窗中 [DataContext] 屬性旁邊的 [新增] 按鈕。

  4. 在 [選取物件] 對話方塊中,確定已清除 [顯示所有組件],接著選取 projectName 命名空間下的 [ShoppingCart],然後按一下 [確定]。

    下圖顯示已選取 [ShoppingCart] 的 [選取物件] 對話方塊。

    [選取物件] 對話方塊

  5. 在 [工具箱] 中,按兩下 TextBlock 控制項使其加入至畫板。

  6. 選取 TextBlock 控制項後,按一下 [屬性] 視窗中 [一般] 之下 [文字] 屬性右邊的屬性標記 (屬性標記看起來像個小方塊)。

  7. 按一下所產生功能表中的 [建立資料繫結]。

  8. 以 [資料內容] 做為繫結型別 (這是 [繫結型別] 清單中的預設值),選取 [路徑] 方塊中的 [ItemCount] 屬性,然後按一下 [確定]。

    下圖顯示已選取 [ItemCount] 屬性的 [建立資料繫結] 對話方塊。

    [建立資料繫結] 對話方塊

  9. 按 F5 以啟動應用程式。

    TextBlock 控制項應顯示預設值 0 做為文字。

請參閱

參考

新增值轉換器對話方塊

概念

使用 XAML 設計工具建立 UI