绑定不适用于XAML中创建的DependencyObject [英] Binding doesn't work on DependencyObject created in XAML
问题描述
我正在尝试使用自定义类在XAML中传递多个CommandParameters.
我创建了一个名为 ValueCommandArgs 的类,该类继承自 DependencyObject ,并且具有两个DepencyProperty(我们将其称为 Value1 和 Value2 ).
应该调用命令并传递该对象的按钮如下所示:
<按钮命令="{Binding ChangeValueCommand}" Content ="Execute Command">< Button.CommandParameter>< args:ValueCommandArgs Value1 ="{Binding TestValue1}" Value2 ="{Binding TestValue2}"/></Button.CommandParameter></按钮>
我确实在命令中获得了一个ValueCommandArgs对象作为参数,但是属性 Value1 和 Value2 始终为空/空./p>
我知道可以通过MultiBinding和Converter来解决,但是我认为尝试这种方法将是一种更清洁的方法.
为什么这行不通?
Binding
需要一个源对象才能提供值.当未指定绑定源(使用 Source
或 ElementName
等)时,例如: Value1 ="{Binding TestValue1}"
使用元素的DataContext
.
args:ValueCommandArgs
对象不会从 Button
元素继承 DataContext
,因为属性值继承特别是关于属性值如何继承的根据元素树中的父子关系在一个元素之间从一个元素到另一个元素.
按钮对象的逻辑树和可视树中都不包含 CommandParameter
属性的值.
在许多情况下,可以通过将值直接绑定到ViewModel来避免具有多个绑定值的 CommandParameter
的需要.
如果无法避免,则可以使用其他类型的绑定标记扩展,例如:https://github.com/JohanLarsson/Gu.Reactive#ninjabinding ,它将使用根 FrameworkElement
作为绑定源.
另一种方法是此博客文章中所示的绑定代理技术: I do get an ValueCommandArgs-Object in my command as paramter, however the properties Value1 and Value2 are always null/empty. I know this can be solved with a MultiBinding and Converter, but I think the way I'm trying it would be a cleaner approach. Why doesn't this work? A The The button object does not include the value of the In many cases the need for such a When it can't be avoided you can use a different type of binding markup extension like: https://github.com/JohanLarsson/Gu.Reactive#ninjabinding that will use the root Another approach would be a binding proxy technique shown in this blog post: How to bind to data when the DataContext is not inherited 这篇关于绑定不适用于XAML中创建的DependencyObject的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!Binding
needs a source object to be able to provide a value. When the Binding source is not specified (with Source
or ElementName
etc.) eg: Value1="{Binding TestValue1}"
the DataContext
of the element is used.args:ValueCommandArgs
object does not inherit the DataContext
from the Button
element because property value inheritance is particularly about how property values can inherit from one element to another on the basis of the parent-child relationships within a tree of elements. CommandParameter
property in its logical nor the visual tree.CommandParameter
with multiple bound values can be avoided by binding the values directly to the ViewModel. FrameworkElement
as the source of the binding.