Skip to main content
 首页 » 编程设计

c#之WPF TextBox UpdateSourceTrigger=LostFocus 不断更新数据

2024年02月05日18lvdongjie

我正在学习 WPF 教程系列。目前我在这一步 http://www.wpf-tutorial.com/data-binding/responding-to-changes/

我遇到的问题是,我希望文本框只在我离开文本框时才更新值。但是,即使 无论是在 TextBox 内部还是外部,当我更改窗口大小时,值都会更新。那不是我所期望的。我的错误在哪里?

这里是您自己测试的简短代码版本:

<Window x:Class="MainWindow" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Title="MainWindow" Height="350" Width="525"> 
    <Grid> 
        <WrapPanel Orientation="Horizontal" Margin="0,10,0,0"> 
            <TextBlock Text="Window dimensions: "/> 
            <TextBox Text="{Binding Width, UpdateSourceTrigger=LostFocus}" Width="50" /> 
            <TextBlock Text=" x " /> 
            <TextBox Text="{Binding Height, UpdateSourceTrigger=PropertyChanged}" Width="50"/> 
        </WrapPanel> 
    </Grid> 
</Window> 

请您参考如下方法:

But even if I'm inside the TextBox the value get's updated when I change the window size.

您自己说过,在更改窗口大小时,值会更新。这是因为文本框失去了焦点。如果您希望文本框即使在失去焦点后仍能获得焦点,您可以通过编程方式将焦点设置到文本框。

第二个文本框<TextBox Text="{Binding Height, UpdateSourceTrigger=PropertyChanged}" Width="50"/>还有UpdateSourceTrigger=PropertyChanged .我希望你解释的不是这种情况,因为 UpdateSourceTrigger=PropertyChanged每当在文本框中输入新字符时都会更新源。