【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 @ 2022-09-07 15:26  宋桓公  阅读(124)  评论(0)    收藏  举报