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);
相关推荐
zzyzxb14 分钟前
WPF 中隧道事件和冒泡事件
wpf
闲人编程19 分钟前
API限流、鉴权与监控
分布式·python·wpf·限流·集群·令牌·codecapsule
TA远方2 小时前
【WPF】桌面程序使用谷歌浏览器内核CefSharp控件详解
wpf·浏览器·chromium·控件·cefsharp·cefsharp.wpf
Macbethad13 小时前
工业设备数据采集主站程序技术方案
wpf
关关长语21 小时前
HandyControl 3.5.x 版本 ListViewItem不显示问题
windows·wpf
Macbethad1 天前
工业设备维护程序技术方案
wpf
Macbethad1 天前
工业设备配方管理系统技术方案
wpf
喵叔哟1 天前
7.日志系统深入
wpf
清风徐来Groot1 天前
WPF布局之Grid
wpf
清风徐来Groot1 天前
WPF布局之WrapPanel
wpf