输入时调用C#getter两次

Ben*_*dEg 3 c# wpf getter binding

为什么c#-getter被调用两次,如果我写了一封信TextBox

在我看来,这很奇怪,因为只有一个元素(Label)绑定到属性以获取值.

这是我的xaml:

<Window x:Class="BindingDebug.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:BindingDebug"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="30" />
            <RowDefinition Height="30" />
            <RowDefinition Height="30" />
            <RowDefinition Height="30" />
        </Grid.RowDefinitions>

        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="auto" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>

        <Label Grid.Row="0" Grid.Column="0" Content="Firstname" />
        <TextBox Grid.Row="0" Grid.Column="1"  x:Name="firstNameTextBox" Height="24" VerticalAlignment="Center" HorizontalAlignment="Stretch"
                    Text="{Binding FirstName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />

        <Label Grid.Row="1" Grid.Column="1" VerticalAlignment="Center" HorizontalAlignment="Left" Content="{Binding FirstName}" />
    </Grid>
</Window>
Run Code Online (Sandbox Code Playgroud)

代码背后:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        this.DataContext = new Model();
    }
}
Run Code Online (Sandbox Code Playgroud)

该模型

public class Model : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private string firstName;

    public string FirstName
    {
        get
        {
            System.Diagnostics.Debug.WriteLine("Get: " + firstName ?? "");
            return firstName;
        }

        set
        {
            firstName = value;
            System.Diagnostics.Debug.WriteLine("Set: " + value ?? "");
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs("FirstName"));
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

或者两次调用getter是否正确?调试输出转到Visual Studio输出窗口.

谢谢!

Nos*_*mus 6

由Microsoft发布于2010年4月28日上午10:10这不是错误.WPF(或任何其他代码)可以出于任何原因随时致电您的财产获取者; 没有规则它只会被调用一次.WPF(和其他呼叫者)希望您的财产遵循.Net指南; 特别是property-getter很快,并且它会从call到call返回相同的值,除非你引发了属性更改通知.

请参阅此处获取链接等:WPF绑定视图作为内容