Binding doesn't work on DependencyObject created in XAML

≡放荡痞女 提交于 2021-02-08 20:36:54

问题


I'm trying to pass multiple CommandParameters in XAML with the use of a custom class.

I have created a class called ValueCommandArgs that inherits from DependencyObject and has two DepencyProperties (lets call them Value1 and Value2 for this example).

The button which is supposed to call a command and pass this object looks like this:

<Button Command="{Binding ChangeValueCommand}" Content="Execute Command">
    <Button.CommandParameter>
        <args:ValueCommandArgs Value1="{Binding TestValue1}" Value2="{Binding TestValue2}" />
    </Button.CommandParameter>
</Button>

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?


回答1:


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



来源:https://stackoverflow.com/questions/26364979/binding-doesnt-work-on-dependencyobject-created-in-xaml

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!