绑定不适用于XAML中创建的DependencyObject [英] Binding doesn't work on DependencyObject created in XAML

查看:52
本文介绍了绑定不适用于XAML中创建的DependencyObject的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用自定义类在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 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.

The 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.

The button object does not include the value of the CommandParameter property in its logical nor the visual tree.

In many cases the need for such a CommandParameter with multiple bound values can be avoided by binding the values directly to the ViewModel.

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 FrameworkElement as the source of the binding.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆