给定一个样式化的 WPF DependencyObject,如何在代码中获取样式键?
我有一组绑定到数据的控件,我想在其中以编程方式将验证器添加到绑定中。目前,我可以迭代可视化树以查找具有绑定的控件,并将验证器添加到这些控件中。但为了进一步指定哪些控件应该具有特定的验证,我想使用样式。所以我的 XAML 如下所示:
<TextBox Name="someTextBox" Style="{StaticResource optionalNumericTextBox}" />
这里,optionalNumericTextBox
样式既用于添加验证错误模板,又作为装饰器来指示此文本框应应用可选的数字验证器。
当我遍历可视化树,发现带有绑定的控件,然后需要确定使用的样式时,就会出现问题。目前我已经尝试过
dependencyObject.GetValue(FrameworkElement.StyleProperty)
,这给了我一种风格对象,但据我所知,该对象不携带 “可选数字文本框”值。是否有可能确定密钥,或者此信息是否会在 XAML 读取器中丢失?
I have a set of controls bound to data, on which I would like to programmaticaly add validators to the bindings. Currently I'm able to iterate over the visual tree to find those controls with bindings, and also add my validators to these controls. But to further specify which controls should have specific validation I wanted to use styles. So my XAML looks like this:
<TextBox Name="someTextBox" Style="{StaticResource optionalNumericTextBox}" />
Here, the optionalNumericTextBox
style serves both adding a validation error template and as a decorator to indicate that this textbox should have the optional numeric validator applied.
The problem occurs when I'm traversing the visual tree, discovers a control with bindings, and then need to determine the style in use. Currently I've tried
dependencyObject.GetValue(FrameworkElement.StyleProperty)
which gives me a Style object but as far as I can tell, this object does not carry the
'optionalNumericTextBox' value. Is it even possible to determine the key or is this information lost in the XAML reader?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用
StaticResourceExtension
时,在将 XAML 转换为 BAML 时,此信息会在编译时丢失。另一方面,使用 DynamicResourceExtension 可以保留密钥,以便可以在运行时解析资源。要找到关键,您需要使用ReadLocalValue()
:问题是,
ResourceReferenceExpression
是内部类型,因此您需要使用反射来拉取拿出钥匙。作为所有这些的替代方案,您是否考虑过劫持
Tag
属性?然后您的代码可以简单地检查
TextBox
上的Tag
属性。When using
StaticResourceExtension
, this information is lost at compile time when converting your XAML to BAML. UsingDynamicResourceExtension
, on the other hand, keeps the key around so the resource can be resolved at runtime. To get at the key, you'll need to useReadLocalValue()
:The problem is,
ResourceReferenceExpression
is an internal type, so you'll need to use reflection to pull out the key.As an alternative to all this, have you considered hijacking the
Tag
property instead?Then your code can simply check the
Tag
property on theTextBox
.