wpf textbox 有焦点 导致后台更新 前台不跟着改变

这个问题可能是由于 WPF 的数据绑定机制导致的。当 TextBox 有焦点时,它会独立于数据绑定进行更新,这可能会导致前台界面不能及时反映后台数据的变化。

1.使用 UpdateSourceTrigger 属性:

在数据绑定时,将 UpdateSourceTrigger 属性设置为 PropertyChanged。这样当 TextBox 的值发生变化时,就会立即更新数据源。

csharp 复制代码
<TextBox Text="{Binding MyProperty, UpdateSourceTrigger=PropertyChanged}" />


//使用 FrameworkElementFactory 创建 TextBox,可以通过以下方式设置数据绑定并指定 UpdateSourceTrigger:

// 创建 FrameworkElementFactory 表示 TextBox
FrameworkElementFactory tbox = new FrameworkElementFactory(typeof(TextBox));

// 设置 Text 属性的数据绑定
Binding binding = new Binding("MyProperty");
binding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
tbox.SetBinding(TextBox.TextProperty, binding);

2...手动触发 INotifyPropertyChanged 事件:

如果您的数据模型实现了 INotifyPropertyChanged 接口,可以在属性值发生变化时手动触发 PropertyChanged 事件。这样前台界面就能及时更新。

csharp 复制代码
private string _myProperty;
public string MyProperty
{
    get { return _myProperty; }
    set
    {
        _myProperty = value;
        OnPropertyChanged(nameof(MyProperty));
    }
}

protected virtual void OnPropertyChanged(string propertyName)
{
    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}

3使用 LostFocus 事件:

您可以监听 TextBox 的 LostFocus 事件,在事件处理程序中手动更新数据源。这样可以确保在 TextBox 失去焦点时,数据源已经被更新。

csharp 复制代码
<TextBox Text="{Binding MyProperty}" LostFocus="TextBox_LostFocus" />
private void TextBox_LostFocus(object sender, RoutedEventArgs e)
{
    // 手动更新数据源
    var textBox = (TextBox)sender;
    var dataContext = (YourDataContext)textBox.DataContext;
    dataContext.MyProperty = textBox.Text;
}

4.使用 Binding.UpdateSourceTrigger 属性:

您也可以在代码中设置 Binding.UpdateSourceTrigger 属性,以控制数据源的更新时机。

csharp 复制代码
var binding = new Binding("MyProperty")
{
    UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
};
textBox.SetBinding(TextBox.TextProperty, binding);
相关推荐
芝麻科技8 小时前
使用ValueConverters扩展实现枚举控制页面的显示
wpf·prism
笑非不退1 天前
Wpf Image 展示方式 图片处理 显示
开发语言·javascript·wpf
△曉風殘月〆1 天前
在WPF中实现多语言切换的四种方式
wpf·多语言切换
笑非不退1 天前
WPF C# 读写嵌入的资源 JSON PNG JPG JPEG 图片等资源
c#·wpf
He BianGu1 天前
演示:基于WPF的DrawingVisual开发的频谱图和律动图
wpf·示波器·曲线图·频谱分析仪·频谱图·高性能曲线·自绘
笑非不退5 天前
WPF 设计属性 设计页面时实时显示 页面涉及集合时不显示处理 设计页面时显示集合样式 显示ItemSource TabControl等集合样式
wpf
△曉風殘月〆5 天前
WPF中的XAML详解
wpf·xaml
ithouse5 天前
使用WPF实现一个快速切换JDK版本的客户端工具
java·开发语言·wpf
河西石头5 天前
WPF之UI进阶--控件样式与样式模板及词典
ui·wpf·样式·模板·控件样式·样式模板·样式词典
TA远方6 天前
【WPF】桌面程序开发之窗口的用户控件详解
c#·wpf·usercontrol·用户控件·控件属性