为什么在更新文本源时不更新文本块

时间:2011-07-10 09:23:26

标签: wpf data-binding

Please Checkout this Pictute

public class Person : INotifyPropertyChanged
{

    private string name;
    // Declare the event
    public event PropertyChangedEventHandler PropertyChanged;
    public Person()
    {
    }
    public string newPerson(string Value)
    {
        this.Name = Value;
        return "";
    }
    public Person(string value)
    {

        this.name = value;

    }
    public string Name
    {

        get { return name; }

        set
        {

            name = value;

            // Call OnPropertyChanged whenever the property is updated

            OnPropertyChanged("Name");

        }

    }
    // Create the OnPropertyChanged method to raise the event

    protected void OnPropertyChanged(string name)
    {

        PropertyChangedEventHandler handler = PropertyChanged;

        if (handler != null)
        {

            handler(this, new PropertyChangedEventArgs(name));

        }

    }

。 XAML:

<Window.Resources>
    <local:Person x:Key="NewPerson" Name="shuvo"/>
    <ObjectDataProvider x:Key="AddNewPerson" ObjectType="{x:Type local:Person}" MethodName="newPerson">
        <ObjectDataProvider.MethodParameters>
            <sys:String>yahoo</sys:String>
        </ObjectDataProvider.MethodParameters>
    </ObjectDataProvider>
</Window.Resources>
<Grid>
    <TextBlock Height="23" HorizontalAlignment="Left" Margin="46,57,0,0" Name="textBlock1" Text="{Binding Source={StaticResource NewPerson},Path=Name}" VerticalAlignment="Top" Width="207" />
    <TextBox Height="23" HorizontalAlignment="Left" Margin="46,149,0,0" Name="textBox1" VerticalAlignment="Top" Width="234" Text="{Binding Source={StaticResource AddNewPerson}, Path=MethodParameters[0],BindsDirectlyToSource=True,Mode=OneWayToSource,UpdateSourceTrigger=PropertyChanged}" />
</Grid>

1 个答案:

答案 0 :(得分:1)

ObjectDataProvider 正在创建 Person 类的新实例,然后调用该新实例的 newPerson 方法。此新实例未连接到您在窗口资源中声明为 NewPerson 的现有 Person 实例。因此,对象数据提供程序正在调用一个无效的方法。

您应该mofify ObjectDataProvider 以使用 ObjectInstance 属性并将其绑定到定义的 NewPerson 的Windows资源。有关详细信息,请参阅here