简单的DataBinding问题

时间:2009-03-07 13:25:53

标签: c# wpf data-binding

我无法弄清楚这个简单绑定有什么问题。 当点击第一个或第二个单选按钮时,不显示名字或姓氏。

1)Xaml

<Window x:Class="WpfApplication2.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WpfApplication2"
    Title="Window1" Height="300" Width="300">
    <Window.Resources>
        <local:Person x:Key="personInfo"/>
    </Window.Resources>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="50" />
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>
        <StackPanel Orientation="Horizontal">
        <RadioButton Name="r1" Click="onClick1">1st person</RadioButton>
        <RadioButton Name="r2" Click="onClick2">2nd person</RadioButton>   
        </StackPanel>
        <StackPanel Grid.Row="1" Orientation="Horizontal">
            <TextBlock Name="t1">First Name</TextBlock>                
            <TextBox Name="fn" Text="{Binding Path=FirstName}"/>

            <TextBlock Name="t2">Last Name</TextBlock>
            <TextBox Name="ln" Text="{Binding Path=LastName}"/>
        </StackPanel>
    </Grid>
</Window>

2)代码隐藏

public partial class Window1 : Window
    {
        Person p = new Person();
        Person[] list ;
        public Window1()
        {
            InitializeComponent();

            list = new Person[2] { new Person { FirstName = "John", LastName = "Smith"},
                                   new Person { FirstName = "Steve", LastName = "King"} };
        }

        public void onClick1(Object h , RoutedEventArgs arg)
        {
            p.FirstName = list[0].FirstName;
            p.LastName = list[0].LastName;
        }

        public void onClick2(Object h, RoutedEventArgs arg)
        {
            p = list[1];

        }
    }

3)Person.cs

class Person : INotifyPropertyChanged
    {
        string firstName;
        string lastName;

        public string FirstName
        {
            get { return firstName; }
            set { firstName = value;
                  OnPropertyChanged("FirstName");
                } 
        }

        public string LastName
        {
            get { return lastName; }
            set { lastName = value;
                   OnPropertyChanged("LastName");
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

非常感谢!

1 个答案:

答案 0 :(得分:2)

您需要在代码中实际设置绑定源,为此需要StackPanel的名称。您必须将名称添加到最后一个堆栈面板。第1行中的那个

<StackPanel 
  ...
  Name="m_panel" />

在事件代码中更新DataContext

public void onClick1(Object h , RoutedEventArgs arg)
{
    p.FirstName = list[0].FirstName;
    p.LastName = list[0].LastName;
    m_panel.DataContext = p;
}

编辑澄清了要命名的StackPanel