WPF(数据更新)

<Window x:Class="WpfApp1.Window1" Title="Window1" 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" Width="800" Height="450" 
        WindowStartupLocation="CenterScreen" mc:Ignorable="d">
    <DockPanel>
        <Image Source="img/aislogo.png" />
        <StackPanel Margin="5" Orientation="Vertical">
            <Slider x:Name="slider1" Margin="5" Background="Red" Maximum="100" Minimum="5" Value="8" />
            <TextBox x:Name="tb1" Text="{Binding ElementName=slider1, Path=Value}" Margin="5" Background="Chocolate" FontSize="20" />
            <TextBox x:Name="tb2" Text="{Binding ElementName=tb1, Path=Text}" Margin="5" Background="Chocolate" FontSize="20" />
        </StackPanel>
    </DockPanel>
</Window>

通过上例可以发现:

  1. 改变slider1值会立即更新到tb1和tb2上
  2. 改变tb1值,值有变化就会更新到tb2上,而只有当tb1失去焦点时才更新到slder1上
  3. 改变tb2值时,只有tb2失去焦点时才更新到tb1和slider1上

 为理解这一区别,需要深入分析这两个控件使用的绑定表达式。当使用OneWay或TwoWay绑定时,改变后的值会立即从源传播到目标。然而,反向的变化传递,从目标到源,未必会立即发生。它们的行为由Binding.UpdateSourceTrigger属性控制。

                                                          UpdateSourceTrigger枚举值

名称说明
PropertyChanged当目标属性发生变化时立即更新源
LostFocus当目标属性发生变化并且目标丢失焦点时更新源
Explicit除非调用BindingExpression.UpdateSource()方法,否则无法更新源
Default根据目标属性的元数据确定更新行为(从技术角度看,是根据FrameworkPropertyMetadata.DefaultUpdateSourceTrigger属性决定更新行为)。大多数属性的默认行为是PropertyChanged,但TextBox.Text属性的默认行为是LostFocus

posted @ 2022-04-12 22:46  Bridgebug  阅读(146)  评论(0编辑  收藏  举报