[WPF] How to bind to data when the DataContext is not inherited

Wireshark抓包分析:如何从HTTP流量中快速定位黑客攻击痕迹(附pcap文件) 本文通过Wireshark实战,详细解析了如何从HTTP流量中快速定位黑客攻击痕迹。文章提供了核心过滤策略,并重点剖析了如何识别SQL注入攻击的流量特征、揭露WebShell的隐蔽通信以及追踪攻击者在横向移动中的行为,帮助安全人员系统性地从pcap文件中还原完整攻击链。 阅读详情

The DataContext property in WPF is extremely handy, because it is automatically inherited by all children of the element where you assign it; therefore you don’t need to set it again on each element you want to bind. However, in some cases theDataContext is not accessible: it happens for elements that are not part of the visual or logical tree. It can be very difficult then to bind a property on those elements…

 

Let’s illustrate with a simple example: we want to display a list of products in aDataGrid. In the grid, we want to be able to show or hide the Price column, based on the value of aShowPrice property exposed by the ViewModel. The obvious approach is to bind the Visibility of the column to the ShowPrice property:

1
2
3
< DataGridTextColumn Header = "Price" Binding = "{Binding Price}" IsReadOnly = "False"
                    Visibility="{Binding ShowPrice,
                        Converter={StaticResource visibilityConverter}}"/>

 

Unfortunately, changing the value of ShowPrice has no effect, and the column is always visible… why? If we look at the Output window in Visual Studio, we notice the following line:

System.Windows.Data Error: 2 : Cannot find governing FrameworkElement or FrameworkContentElement for target element. BindingExpression:Path=ShowPrice; DataItem=null; target element is ‘DataGridTextColumn’ (HashCode=32685253); target property is ‘Visibility’ (type ‘Visibility’)

 

The message is rather cryptic, but the meaning is actually quite simple: WPF doesn’t know which FrameworkElement to use to get the DataContext, because the column doesn’t belong to the visual or logical tree of theDataGrid.

 

We can try to tweak the binding to get the desired result, for instance by setting the RelativeSource to theDataGrid itself:

1
2
3
4
< DataGridTextColumn Header = "Price" Binding = "{Binding Price}" IsReadOnly = "False"
                    Visibility="{Binding DataContext.ShowPrice,
                        Converter={StaticResource visibilityConverter},
                        RelativeSource={RelativeSource FindAncestor, AncestorType = DataGrid }}"/>

 

Or we can add a CheckBox bound to ShowPrice, and try to bind the column visibility to theIsChecked property by specifying the element name:

1
2
3
4
< DataGridTextColumn Header = "Price" Binding = "{Binding Price}" IsReadOnly = "False"
                    Visibility="{Binding IsChecked,
                        Converter={StaticResource visibilityConverter},
                        ElementName = chkShowPrice }"/>

 

But none of these workarounds seems to work, we always get the same result…

At this point, it seems that the only viable approach would be to change the column visibility in code-behind, which we usually prefer to avoid when using the MVVM pattern… But I’m not going to give up so soon, at least not while there are other options to consider ;)

 

The solution to our problem is actually quite simple, and takes advantage of theFreezable class. The primary purpose of this class is to define objects that have a modifiable and a read-only state, but the interesting feature in our case is that Freezable objects can inherit the DataContext even when they’re not in the visual or logical tree. I don’t know the exact mechanism that enables this behavior, but we’re going to take advantage of it to make our binding work…

 

The idea is to create a class (I called it BindingProxy for reasons that should become obvious very soon) that inheritsFreezable and declares a Data dependency property:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class BindingProxy : Freezable
{
    #region Overrides of Freezable
    protected override Freezable CreateInstanceCore()
    {
        return new BindingProxy();
    }
    #endregion
    public object Data
    {
        get { return ( object )GetValue(DataProperty); }
        set { SetValue(DataProperty, value); }
    }
    // Using a DependencyProperty as the backing store for Data.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty DataProperty =
        DependencyProperty.Register( "Data" , typeof ( object ), typeof (BindingProxy), new UIPropertyMetadata( null ));
}

 

We can then declare an instance of this class in the resources of the DataGrid, and bind the Data property to the current DataContext:

1
2
3
< DataGrid.Resources >
    < local:BindingProxy x:Key = "proxy" Data = "{Binding}" />
</ DataGrid.Resources >

 

The last step is to specify this BindingProxy object (easily accessible withStaticResource) as the Source for the binding:

1
2
3
4
< DataGridTextColumn Header = "Price" Binding = "{Binding Price}" IsReadOnly = "False"
                    Visibility="{Binding Data.ShowPrice,
                        Converter={StaticResource visibilityConverter},
                        Source={StaticResource proxy}}"/>

 

Note that the binding path has been prefixed with “Data”, since the path is now relative to theBindingProxy object.

The binding now works correctly, and the column is properly shown or hidden based on theShowPrice property.

 

From: http://www.thomaslevesque.com/tag/datacontext/

蓝牙攻防实战指南:低功耗蓝牙 Bluetooth Low Energy(也称Bluetooth Smart)是经典蓝牙(Bluetooth Classic)的演进版本,设计目标是实现极低功耗,适用于无需频繁更换电池的设备,如智能手环、健康监测器、蓝牙标签等。Bluetooth Low Energy 是一项极具前景的无线通信技术,它以极低的功耗实现了短距离高效通信,广泛应用于智能设备和物联网领域。然而,其简化的协议结构和配对机制也带来了不小的安全挑战。 阅读详情

相关推荐

Autodesk激活无无网络选项?许可类型与脱机激活排查修复指南

软件许可激活是保障正版授权正常使用的核心环节,常见的授权模式包括单机版许可和网络版许可,两者在认证机制和应用场景上有所区别。单机版离线授权依托 FlexNet Licensing Service 等底层服务组件,在断网或内网环境下为用户提供可靠的技术支持与授权验证路径。然而在实际部署中,激活窗口并不总是显示“无网络激活方式”入口,这可能与许可类型选择、网络环境干扰、组件安装残留或系统时间偏差有关。理解入口的动态呈现逻辑与排查顺序,有助于在 AutoCAD、Revit 等 Autodesk 产品中高效解决脱机

weixin_28709649的博客 368

[WPF] 绑定元素不在可视树或逻辑树上时如何绑定(Cannot find governing FrameworkElement or FrameworkContentElement)

原文地址 WPF中的DataContext属性非常方便,但在某些情况下,DataContext是不可访问的,比如,当你想绑定的元素不属于其逻辑树或可视树时,想正常使用绑定就可能非常困难…… 让我们给一个简单的例子予以说明:我们要在DataGrid中显示产品列表。 在其中,我们希望能够基于ViewModel中公开的ShowPrice属性的值来显示或隐藏Price列。 一种明显的方法是将列的Visibility绑定到ShowPrice属性: <DataGridTextColumn Header="Pr.

wdyxyyp的博客 2065

从零到一:在K210上实现YOLO模型在线训练与部署全流程

本文详细介绍了在K210芯片上实现YOLO模型在线训练与部署的全流程,涵盖数据采集、模型优化、量化转换及内存管理等关键环节。通过实战案例和代码示例,帮助开发者高效利用K210的超低功耗特性与YOLO模型的实时检测能力,适用于边缘计算和物联网应用场景。

weixin_29094539的博客 358

WPF Angle RotateTransform.Angle Double 找不到目标元素的管理 FrameworkElement 或 FrameworkContentElement

找不到目标元素的管理 FrameworkElement 或 FrameworkContentElement。

^@^lemon tea^@^ 1704

unity 在透明物体上投射阴影

unity版本:2019.4.16 创建一个shader,代码如下: Shader "ChuckLee/ARShadow" { Properties { _ShadowColor("Shadow Color", Color) = (0.1, 0.1, 0.1, 0.53) } SubShader { Tags{ "RenderType" = "Transparent" "Queue" = "Geometry+1" } Blend SrcAlpha OneMinusSrcAlph

Abel02的博客 2960

C# 操作Excel的时候,出现"被呼叫方拒绝接受呼叫的异常"的解决方案(参考官方给出的解决方案)

首先官方有对这个错误给出解释和解决方案,连接如下: https://docs.microsoft.com/zh-cn/previous-versions/ms228772(v=vs.120)#%E5%8F%AF%E9%9D%A0%E7%BC%96%E7%A8%8B 简单来说,貌似是线程问题,我猜。。。 之前我尝试着在代码中添加 Thread.Sleep(1000); 来进行解决,这种办...

Ck_Max的博客 5778

WPF之使用“依赖属性”实现动态添加DataGrid“头”和“列”(MVVM模式)

1、首先自定义控件——DataGridEx 添加依赖属性:DynamicBindHeadersCols /// <summary> /// DataGridEx.xaml 的交互逻辑 /// </summary> public partial class DataGridEx : DataGrid { /// <summary> /// 动态绑定DataGrid头和列 /// &

Grape-!的博客 2798

树莓派4B保姆级教程:从零配置Python虚拟环境到PySide2开发全流程(含避坑指南)

本文提供树莓派4B上配置Python虚拟环境及PySide2 GUI开发的完整教程。针对armv7l架构的特殊性,详细讲解了从系统准备、虚拟环境创建到PySide2安装的避坑指南,并重点解决了跨平台UI文件处理等常见难题,帮助开发者构建稳定高效的开发环境。

9q8w7e6r5的博客 827

wpf 解决Cannot find governing FrameworkElement or FrameworkContentElement for target element.

在这个样式中,我们在Style.Resources中定义了一个BindingProxy对象,并试图设置它的TmpData属性绑定到当前的数据上下文({Binding})。但是,Style.Resources并不是逻辑树或可视树的一部分,因此它没有继承数据上下文。我们可以使用一个技巧:将BindingProxy放置在模板中的某个FrameworkElement的Resources中,这样它就会继承该元素的数据上下文。这个错误通常发生在尝试绑定时,绑定系统无法找到合适的数据上下文。类,用于中转数据绑定。

一个编程的同学 826

ICCompiler II学习笔记(一)ICC II使用全流程 overview

学习笔记同步发布在我的个人网站上,欢迎来访查看。 个人学识有限,理解可能有误,仅供参考。 文章目录一、前言二、 ICC II 简介和 GUI2.1 Blocks 和 Design Libraries2.2 Objects2.3 Application Options三、Design Setup四、APR flow五、 课程主题:如何用 ICC II来实现最好的PPA 一、前言 现在的芯片都在追求一个极致的PPA 芯片的生成可以分为以下 5大步骤: Front-end Design:前端设计,最终产生

一名FPGA芯片设计爱好者的技术博客 2万+

NHANES数据库的介绍及使用(一)

一、数据库概况 NHANES(National Health and Nutrition Examination Survey)是一项旨在评估美国成人和儿童健康和营养状况的研究计划,计划始于20世纪60年代初期,是一项针对不同人群或健康主题的调查。 1999年该调查成为一项持续计划,涉及各种健康和营养测量,项目每年调查一个全国代表性的样本,约5000人,这些人群位于全国各县,每年对其中15个县进行访问。 NHANES访谈部分包括人口统计学、社会经济学、饮食和健康相关问题。体检部分包括生理测量、实验室检查等

Christina 5万+

[WPF] How to bind to data when the datacontext is not inherited

[WPF] How to bind to data when the datacontext is not inherited 原文:[WPF] How to bind to data when the datacontext is not inherited原文地址:http://www.thomaslevesque.com/2011/03/...

weixin_30466421的博客 104

基于STM32LXXX的模数转换芯片ADC(CMS24AD2001)驱动C程序设计

/ 电压 = (原始值 / 2^23) * Vref (注意:24位有符号数范围为 -2^23 到 2^23-1)//---------------- 硬件端口映射 (请根据实际电路修改) ----------------ADC_SCLK_HIGH();- PGA 放大倍数可选:1、2、4、8、16、32、64、128、256;//---------------- 宏定义操作 -------------------//---------------- 函数声明 -------------------

myron6688的博客 169

How to bind to data when the DataContext is not inherited【项目】

http://www.thomaslevesque.com/2011/03/21/wpf-how-to-bind-to-data-when-the-datacontext-is-not-inherited/ The DataContext property in WPF is extremely handy, because it is automatically inherited by al...

weixin_30699465的博客 143

OV9734 DATASHEET,完整规格书

OV9734完整规格书,包括电气参数,尺寸规格,寄存器配置表等

温度PID控制PLC程序

温度PID稳定控制程序,适用于欧姆龙PLC,对其他PLC也具有很大参考价值

wpf 数据验证

前言 由于业务需要,需要使用TextBox输入数字,包括小数。所以需要对TextBox的输入数据进行验证。使用的办法分为以下两种 方法一:Validation + Parameter 使用Binding.ValidationRules限制输入值的大小。 xaml定义 <UserControl.Resources> <rule:ValidationParams x:Key="validationParams0"/> </UserControl.Resources>

weixin_45057600的博客 2169

华为的C语言编程规范.pdf

华为技术有限公司内部技术规范。本规范制定了编写C语言程序的基本原则、规则和建议。从代码的清晰、简洁、可测试、安全、程序效率、可移植各个方面对C语言编程作出了具体指导。

C# WinForm 基于DirectShow.dll编写的程序,可边预览边保存视频,音频和图片

基于微软的DirectShow.dll的二次开发1.自动识别连接的摄像头跟麦克风且可以对其进行选择(默认选中第一个)2.可录制wmv和avi两种格式的视频并且都带有音频,avi可以录制的分辨率和帧数进行选择,wmv默认进行了淸晰度优化如不喜欢可去除代码中有相关提示3.可在预览点开之后进行拍照,也可边录制视频边拍照4.添加了视频和音频的压缩功能(酌情使用)这次二次开发发现C#对DirectShow的相关信息太少,这次做完也不敢藏私共享出来,还望大家指正

[WPF] 使用自定义验证规则实现简单数据校验及绑定的项目

项目说明:将来自数据源的数据点画在Chart上,需要选择横轴数据源XAxis、纵轴数据源YAxis、以及选择起始时间和终止时间。 数据源来自于一个DataTable,有Date数据(横轴),以及其它各项Data1,Data2等(纵轴) 不同的纵轴数据源有不同的时间长度(按月份计数),所以在切换纵轴时,需要绑定不同的数据校验Max值,对输入的起始时间和终止时间做数据校验 (由于所用验证规则相同,故将只用起始时间做说明) 先搭建一个简单的属性界面: <!--X轴部分--> <ComboBo.

wdyxyyp的博客 697

Windows System Error Codes (exit codes)

Improve your productivity and save time.  Let your system work for you. Description The Command and WinCommand task sometimes do not return any error messages, when your batch files fail.  These t

lovenjoy的专栏 9103

Windows系统常见错误大全

CMOS battery failed  CMOS电池失效。一般出现这种情况就是说明给主板CMOS供电的电池已经快没电了,需要朋友们及时更换主板电池。  CMOS check sum error-Defaults loaded  CMOS执行全部检查时发现错误,要载入系统预设值。一般来说出现这句话有两种解释:一种是说主板CMOS供电电池快要没电了,朋友们可以先换个电池试试看;第二种解释是如果更换电

mxxiang的专栏 8787

WPF System.Windows.Data Error: 17 数据校验模板绑定错误

错误定位:Path=AdornedElement.(Validation.Errors)[0].ErrorContent修改为:Path=AdornedElement.(Validation.Errors).CurrentItem.ErrorContentCurrentItem可能识别不了,也可以改为:Path=AdornedElement.(Validation.Errors)/ErrorCon...

hanna_123的博客 1504

微软错误代码

2.1  中文0 操作成功完成。1 功能错误。2 系统找不到指定的文件。3 系统找不到指定的路径。4 系统无法打开文件。5 拒绝访问。6 句柄无效。7 存储控制块被损坏。8 存储空间不足,无法处理此命令。9 存储控制块地址无效。10 环境错误。11 试图加载格式错误的程序。12 访问码无效。13 数据无效。14 存储器不足,无法完成此操作。15 系统找不到指定的驱动器。16 无法删除目录。17 系...

余生以学 1万+

关于SpringBoot整合Swagger2出现的问题综合及解决方案

错误信息如下:Unable to infer base url. This is common when using dynamic servlet registration or when the API is behind an API Gateway. The base url is the root of where all the swagger resources are serve...

初学程序员 4万+

项目引用element-ui时报错module not find

Element官网:http://element-cn.eleme.io/#/zh-CN/component/quickstartcnpm 1.安装npm npm install npm i element -ui -S//npm的方式安装element-ui 2.安装cnpm cnpm install cnpm install element-ui --save//cnpm的方式安装eleme...

weixin_44448747的博客 3867
上一篇: MVVM: Good way to close dialog and set DialogResult
下一篇: ASP.net MVC4 + HTML5 + JS 学习贴
wmjcom
博客等级 码龄24年 71粉丝 48原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值