Binding does not work on DependencyObject created in XAML

I am trying to pass multiple CommandParameters in XAML using a custom class.

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

The button that should call the 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 am getting ValueCommandArgs-Object in my command as a parameter, however the Value1 and Value2 properties are always null / empty .

I know it can be solved with MultiBinding and Converter, but I think I am trying to do this in a cleaner approach.

Why doesn't it work?

+3


source to share


1 answer


A Binding

requires the original object to be able to supply the value. If the binding source is not specified (with Source

or ElementName

, etc.), For example: the element is Value1="{Binding TestValue1}"

used DataContext

.

An object args:ValueCommandArgs

does not inherit DataContext

from an element Button

, because property value inheritance specifically refers to how property values ​​can be inherited from one element to another based on parent-child relationships in the element tree .

The button object does not include the value of a property CommandParameter

in its logical or visual tree.



In many cases, the need for one CommandParameter

with multiple bound values ​​can be eliminated by binding the values ​​directly to the ViewModel.

If this cannot be avoided, you can use another type of binding markup extension, for example: https://github.com/JohanLarsson/Gu.Reactive#ninjabinding , which will use the root FrameworkElement

as the binding source.

Another approach would be the proxy technology binding shown in this blog post: How to bind to data when DataContext is not inherited

0


source







All Articles