如果我在 TextBox
中写了一封信,为什么 c#-getter 会被调用两次?
在我看来,这很奇怪,因为只有一个元素 (Label
) 绑定(bind)到属性以获取值。
这是我的 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>
代码隐藏:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = new Model();
}
}
模型
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"));
}
}
}
}
或者 getter 被调用两次是否正确?调试输出转到 Visual Studio 输出窗口。
谢谢!
最佳答案
Microsoft 于 2010 年 4 月 28 日上午 10:10 发布这不是错误。 WPF(或任何其他代码)可以出于任何原因随时调用您的属性 getter ;没有规定它只会被调用一次。 WPF(和其他调用者)希望您的属性(property)遵循 .Net 准则;特别是 property-getter 速度很快,并且它将在每次调用中返回相同的值,除非您发出了属性更改通知。
请在此处查看链接等:WPF Binding View as Content
关于C# getter 在输入时被调用两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33239975/