2013-01-18 77 views
0

我正在嘗試遵循數據綁定到clr對象的代碼示例。無法獲取對Xaml中的clr對象進行數據綁定的引用

示例指出

<DockPanel 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:c="clr-namespace:SDKSample"> 
    <DockPanel.Resources> 
    <c:MyData x:Key="myDataSource"/> 
    </DockPanel.Resources> 
    <DockPanel.DataContext> 
    <Binding Source="{StaticResource myDataSource}"/> 
    </DockPanel.DataContext> 
    <Button Background="{Binding Path=ColorName}" 
      Width="150" Height="30">I am bound to be RED!</Button> 
</DockPanel> 

然而,我似乎有得到一個參考值I創建的對象(在C#)從與在我XAML

<Page 
    x:Class="HelloWindows.MainPage" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:local="using:HelloWindows" 
    xmlns:src="clr-namespace:HelloWindows" 
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
    mc:Ignorable="d"> 

    <Page.Resources> 
     <src:MainPage+Person x:key="person" /> 
    </Page.Resources> 

這裏的問題是我的C#

public Person person = new Person(); 

    public class Person 
    { 
     public String name { get; set; } 
    } 

我創建瞭如圖所示的「src」命名空間。但是,Visual Studio不識別「Person」,並且希望在其前面添加「MainPage + Person」。我收到以下錯誤

添加到IDictionary中的所有對象都必須具有Key屬性或與其關聯的其他類型的鍵。

所以我很困惑這個,也關於「MainPage + Person」。我會假設我需要一種方法來告訴XAML不僅僅是對象的類型,而且還得到了我創建的實際對象的句柄。

回答

1

不幸的是,對於WPF和Windows應用商店應用程序的XAML語法略有差異,您將面臨挑戰。 DockPanel示例是WPF(DockPanel不是本機Windows應用商店控件),並且您的MainPage似乎來自Windows應用商店應用。

xmlns:src="clr-namespace:HelloWindows" 

改變你的名字空間聲明,

xmlns:src="using:HelloWindows" 

usingclr-namespace Windows應用商店的版本。

+0

謝謝你幫助吉姆。我現在使用的是,但我仍然不知道將CLR(稱爲「人」)與XAML鏈接的位置。我相信它只是給了別名的「鑰匙」。我嘗試了但似乎只想解析爲local:MainPage –

+0

應該在假設Person類駐留HelloWindows命名空間。這聽起來像你可能將Person作爲嵌套在MainPage類中的類 - 可能不是你想要的。 –

+0

是的。就是這樣。我將該定義移到了MainPage類之外,並解決了我的問題。謝謝吉姆 –

相關問題