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);
相关推荐
c#上位机1 天前
wpf之Border
c#·wpf
SunflowerCoder1 天前
WPF迁移avalonia之图像处理(一)
图像处理·wpf·avalonia
周杰伦fans1 天前
WPF中的DataContext以及常见的绑定方式
wpf
没有bug.的程序员2 天前
Redis 数据结构全面解析:从底层编码到实战应用
java·数据结构·redis·wpf
somethingGoWay2 天前
wpf 自定义输入ip地址的文本框
wpf
秋月的私语2 天前
Wpf程序屏幕居中问题修复全记录
wpf
我要打打代码2 天前
WPF启动窗体的三种方式
wpf
R瑾安2 天前
mysql集群部署(Mysql Group Replication)
数据库·mysql·wpf
c#上位机2 天前
wpf中资源的使用
c#·wpf
Vae_Mars3 天前
WPF中的静态资源和动态资源
wpf