WPF使用INotifyPropertyChanged实现文本框同步更新标签内容问题排查
问题排查及修复方案
存在的问题清单:
- 核心问题:
TextBox的Text属性未和MyBindedVal建立绑定,修改TextBox内容时完全不会触发MyBindedVal的set逻辑,自然无法同步到Label MyBindedVal的set逻辑顺序错误:应该先给字段赋值,再触发PropertyChanged通知,否则通知触发时界面读取到的还是旧值NotifyPropertyChanged方法的空判断逻辑错误:当前只判断了属性名不为空,没有判断PropertyChanged事件是否有订阅者,无订阅者时调用会抛出空引用异常- Label的绑定参数冗余:
UpdateSourceTrigger仅对指向源的绑定(TwoWay/OneWayToSource)生效,Label用OneWay绑定完全不需要这个参数,写了也不会生效
修正后的代码
MainWindow.xaml.cs
using System.ComponentModel; using System.Windows; namespace Databinding3 { public partial class MainWindow : Window, INotifyPropertyChanged { private string myBindedVal = "...."; public MainWindow() { InitializeComponent(); } public string MyBindedVal { get => myBindedVal; set { // 先赋值再发通知 myBindedVal = value; NotifyPropertyChanged(nameof(MyBindedVal)); } } public event PropertyChangedEventHandler PropertyChanged; private void NotifyPropertyChanged(string propertyName) { // 先判断事件是否有订阅者,避免空引用异常 PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } }
MainWindow.xaml
<Window x:Class="Databinding3.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:Databinding3" mc:Ignorable="d" Title="MainWindow" Height="450" Width="800"> <Grid> <Grid.RowDefinitions> <RowDefinition></RowDefinition> <RowDefinition></RowDefinition> </Grid.RowDefinitions> <!-- 给TextBox添加和MyBindedVal的双向绑定,修改时实时同步到源 --> <TextBox x:Name="txtbx_name" Text="{Binding MyBindedVal, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}}, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" HorizontalAlignment="Center" Height="57" TextWrapping="Wrap" VerticalAlignment="Center" Width="594"/> <!-- 移除Label绑定中冗余的UpdateSourceTrigger参数 --> <Label Content="{Binding MyBindedVal, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}}, Mode=OneWay}" HorizontalAlignment="Center" Height="44" Grid.Row="1" VerticalAlignment="Center" Width="594"/> </Grid> </Window>
修复后修改TextBox内容即可实时同步到Label显示。
内容的提问来源于stack exchange,提问作者user3884423
相关产品推荐
相关产品推荐

