将类实例绑定到控件

时间:2012-02-18 14:44:18

标签: wpf data-binding

我正在使用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;
            }
        }  

    }

当我构建解决方案时,我收到错误:

  

错误1''local'是未声明的前缀。第7行,第10位。' XML是   不   有效。 C:\ Users \ Admin \ Desktop \ DataBinding_01 \ DataBinding_01 \ MainWindow.xaml 7 10 DataBinding_01

为什么以及如何解决?

2 个答案:

答案 0 :(得分:5)

您需要指定local namespace 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">

答案 1 :(得分:2)

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

xmlns:local="clr-namespace:myNameSpace"