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);
相关推荐
周杰伦fans5 小时前
.NET AOT技术深度解析:为什么WPF不支持而Avalonia/UWP支持?
.net·wpf
雨浓YN6 小时前
WPF MVVM 模式(调Prism库)项目创建笔记 —— 包含C++/CLI OpenCV互操作
c++·笔记·wpf
七夜zippoe6 小时前
DolphinDB数据模型:表、分区与分布式表
分布式·wpf·数据模型··dolphindb
一念春风1 天前
Qwen2.5 (AI模型 PC搭建)
人工智能·ai·c#·wpf·模型
互联网散修1 天前
鸿蒙跨设备实时绘图同步:从零到一实现分布式画板
分布式·wpf·harmonyos
晓纪同学2 天前
WPF-09 命令系统
wpf
晓纪同学2 天前
WPF-10资源系统
wpf
七夜zippoe2 天前
DolphinDB集群部署:从单机到分布式
分布式·wpf·单机·dolphindb·分集群
波波0073 天前
写出稳定C#系统的关键:不可变性思想解析
开发语言·c#·wpf
bugcome_com3 天前
从 MVVMLight 到 CommunityToolkit.Mvvm:MVVM 框架的现代化演进与全面对比
wpf