1. 程式人生 > >wpf 如何將名稱空間匯入 XAML

wpf 如何將名稱空間匯入 XAML

若要在 XAML 中使用自定義控制元件和第三方控制元件,需要匯入名稱空間和引用程式集。 有關更多資訊,請參見 WPF XAML 的 XAML 名稱空間和名稱空間對映。

在 XAML 匯入本地名稱空間
建立一個名為“DemoApplication”的新 WPF 應用程式專案。 有關更多資訊,請參見如何:建立新的 WPF 應用程式專案。
向 DemoApplication 專案中新增一個名為“DemoControl.xaml”的新使用者控制元件 (WPF) 項。 有關更多資訊,請參見如何:向 WPF 專案中新增新項。
在“生成”選單上選擇“生成解決方案”以生成解決方案。
在設計器中開啟 MainWindow.xaml。
在 XAML 檢視中,在 Window 開始標記中的第二個 xmlns 對映之後插入一個新行。
鍵入 xmlns:dc= 並從 IntelliSense 列表中選擇“程式集 DemoApplication 中的 DemoApplication”。
設計器將為 DemoApplication 名稱空間插入一個名稱空間對映。
XAML

<Window x:Class="DemoApplication.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:dc="clr-namespace:DemoApplication"
    Title="MainWindow" Height="300" Width="300">
    <Grid>

    </Grid>
</Window
>

在 Grid 元素的開始標記之後,鍵入

  <Grid>
        <dc:DemoControl />
    </Grid>

在 XAML 中匯入第三方名稱空間
向 DemoApplication 解決方案中新增一個名為“VendorControlLibrary”的新 WPF 使用者控制元件庫專案。 生成 DemoApplication 解決方案時,將為該解決方案中的每個專案建立一個程式集。 有關更多資訊,請參見如何:建立 WPF UserControl 庫專案。
在 DemoApplication 專案中,新增對 VendorControlLibrary 專案的專案引用。 有關更多資訊,請參見如何:新增或移除引用使用 ” 新增引用 ” 對話方塊。
在“生成”選單上選擇“生成解決方案”以生成解決方案。
在設計器中開啟 MainWindow.xaml。
在 XAML 檢視中,在 Window 開始標記中的第三個 xmlns 對映之後插入一個新行。
鍵入 xmlns:vc= 並從 IntelliSense 列表中選擇“程式集 VendorControlLibrary 中的 VendorControlLibrary”。
Intellisense 將為 VendorControlLibrary 名稱空間插入一個名稱空間對映,該名稱空間在 VendorControlLibrary.dll 程式集中定義。
XAML

<Window x:Class="DemoApplication.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:dc="clr-namespace:DemoApplication"
    xmlns:vc="clr-namespace:VendorControlLibrary;assembly=VendorControlLibrary"
    Title="MainWindow" Height="300" Width="300">
    <Grid>
        <dc:DemoControl />
    </Grid>
</Window>

在 DemoControl 元素的結束標記之後,鍵入

 <Grid>
        <dc:DemoControl />
        <vc:UserControl1 />
    </Grid>