【wpf】如果让Bingding 如何让后台数据强制更新界面

前言        

这里讲的不是简单的后台数据通知前台变换,而是在一段代码中,我的一个属性发生多次变化,前台也必须发生多次变化。

需求

我调用http,有个接收返回值的TextBox,但是我想在点击Post按键一开始就清理掉TextBox的显示,然后最后将接收值赋值给TextBox。

也就是在一段代码中我两次操作TextBox(通过bindding的方式),但是你会发现,第一次的清空是无效的。

解决方案

所以我需要这么做:

public static class DispatcherHelper
    {
        [SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
        public static void DoEvents()
        {
            DispatcherFrame frame = new DispatcherFrame();
            Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Background, new DispatcherOperationCallback(ExitFrames), frame);
            try { Dispatcher.PushFrame(frame); }
            catch (InvalidOperationException) { }
        }
        private static object ExitFrames(object frame)
        {
            ((DispatcherFrame)frame).Continue = false;
            return null;
        }

    }

然后这么写:

//之前清除返回值, 这样写可以让清楚立即生效
    System.Windows.Threading.Dispatcher.CurrentDispatcher.Invoke(new Action(() => {
        Response = "";
    }));
    DispatcherHelper.DoEvents();  // 强制更新显示  

这样写清除才会立即生效。Response 和前台的TextBox是双向绑定的关系。

完整代码:

BtnGetCMD = new DelegateCommand<string>((content_type) => {
    //之前清除返回值, 这样写可以让清楚立即生效
    System.Windows.Threading.Dispatcher.CurrentDispatcher.Invoke(new Action(() => {
        Response = "";
    }));
    DispatcherHelper.DoEvents();  // 强制更新显示  

    string url = System.IO.Path.Combine(ipAddr, subPath);
    if (string.IsNullOrEmpty(url))
    {
        MessageBox.Show("请输入url");
        return;
    }
    string body = request;
    string result = rqh.Get(url, content_type);

    //显示返回值
    Response = result;
});

结果展示 

 好了,如果对你有帮助,请点个赞~~~

posted @   宋桓公  阅读(107)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示