2012-02-18 86 views
0

我正在学习使用this tutorial的WPF数据绑定。将类实例绑定到控件

这是我的XAML:

Window x:Class="DataBinding_01.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"   
     Title="MainWindow" Height="350" Width="525"> 

    <Window.Resources> 
     <local:Person x:Key="PersonDataSource" Name="Joe"/> 
    </Window.Resources> 

    <DockPanel Height="Auto" Name="panel" Width="Auto" LastChildFill="True"> 
     <TextBox DockPanel.Dock="Top" Height="23" Name="txtName" Width="Auto" /> 
     <Button Content="Button" Name="button1" Width="Auto" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" Click="button1_Click" /> 
    </DockPanel> 
</Window> 

这里是我的代码:

public partial class MainWindow : Window 
    { 
     Person myPerson = null; 
     public MainWindow() 
     { 
      InitializeComponent(); 
      myPerson = this.Resources["PersonDataSource"] as Person; 
      myPerson.NameProperty = "hi, again!"; 
     }  
    } 

    public class Person 
    { 

     Person() 
     { 
      NameProperty = "hi"; 
     } 

     Person(String _name) 
     { 
      NameProperty = _name; 
     } 

     private String name = ""; 
     public String NameProperty 
     { 
      get { return name; } 
      set 
      { 
       name = value; 
      } 
     } 

    } 

当我建立的解决方案,我得到的错误:

Error 1 ''local' is an undeclared prefix. Line 7, position 10.' XML is not valid. C:\Users\Admin\Desktop\DataBinding_01\DataBinding_01\MainWindow.xaml 7 10 DataBinding_01

为什么和如何才能我修复它 ?

回答

5

你需要指定localnamespace in XAML指向您Person的类命名空间:

如果Person类的DataBinding_01命名空间:

<Window x:Class="DataBinding_01.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:local="clr-namespace:DataBinding_01"   
     Title="MainWindow" Height="350" Width="525"> 

在您的样本文章:

<Window 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:local="clr-namespace:BindingSample"> 
2

您需要定义本地myNameSpace是您的名字空间在窗口部分。通常是项目的名称。

xmlns:local="clr-namespace:myNameSpace"