1

I've create a simple app (in Visual Studio 2013.) and add this code:

<Grid Grid.Row="1">
    <StackPanel x:Name="spPerson">
        <TextBox Text="{Binding FirstName}"/>
        <TextBox Text="{Binding LastName}"/>
        <TextBox Text="{Binding Email}"/>
    </StackPanel>
</Grid>
<Grid Grid.Row="2">
    <Button Click="Button_Click" Content="Click"/>
</Grid>

C#:

public async void This()
{
    Person person = new Person();
    person.LastName = "Иванов";
    person.FirstName = "Иван";
    person.Email = "ivan.ivanov@foo.com";
    spPerson.DataContext = person; 
}

private void Button_Click(object sender, RoutedEventArgs e)
{
    Person person = new Person();
    person.LastName = "ss";
}

And class file:

public class Person : INotifyPropertyChanged
{
    private string _lastName; private string _firstName; private string _email;

    public string LastName
    {
        get { return _lastName; }
        set { SetProperty(ref _lastName, value); }
    }

    public string FirstName
    {
        get { return _firstName; }
        set { SetProperty(ref _firstName, value); }
    }

    public string Email
    {
        get { return _email; }
        set { SetProperty(ref _email, value); }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    protected bool SetProperty<T>(ref T storage, T value, [CallerMemberName] String propertyName = null)
    {
        if (object.Equals(storage, value)) return false;
        storage = value; this.OnPropertyChanged(propertyName);
        return true;
    }

    protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
    { 
        var eventHandler = this.PropertyChanged; 
        if (eventHandler != null) 
        { 
            eventHandler(this, new PropertyChangedEventArgs(propertyName)); 
        } 
     }
}

Now when I clicking the button "Button_Click" it doent change information in stackpanel. What I'm doing wrong?

"""I'm writing this because my "post is mostly code".""""

4

1 回答 1

3

Because the person whose LastName you're changing is not bound to the stack panel. You need to grab the object that you used in the first place to bind to the stack panel, and change that object's properties.

Try something like this:

private void Button_Click(object sender, RoutedEventArgs e)
{
    Person person = spPerson.DataContext as Person;

    if(person != null)
      person.LastName = "ss";
}

Edit

To clarify: you're using the Observer pattern, which works like this:

You create a person object (on your code, that would be the person named "Иван"), and then you create a binding between the first TextBox view and the person object. Whenever the person object changes, it will notify all observers (i.e., the 3 TextBoxes) that it has changed. The TextBoxes will react to this notification by changing their text and displaying the new values.

More info: http://www.oodesign.com/observer-pattern.html

于 2013-09-01T21:00:28.547 回答