Are “{Binding Path=.}” and “{Binding}” really equal

后端 未结 4 1406
夕颜
夕颜 2020-11-28 08:44

In my WPF project, I have a ListBox that displays items from a List collection. I wanted to make the text of these items editable, so I wrapped ea

相关标签:
4条回答
  • 2020-11-28 09:05

    In short, the difference between the two is analogous with the difference between the traditional pass by value and pass by reference. (FYR - What's the difference between passing by reference vs. passing by value?)

    However I don't understand why simply using {Binding} didn't work (it raised a "Two-way binding requires Path or XPath" exception)

    Lets assume here for now that {Binding} can be used for two way binding. In general {Binding} creates a value based link with datacontext which does not allow updating the datacontext.

    Whereas {Binding Path=.} creates reference based link with the memory area referenced by the 'Path' which allows updating the value through reference.(in this case 'dot' the current datacontext).

    Hope this helps!

    0 讨论(0)
  • 2020-11-28 09:07

    The documentation states that {Binding} is equivalent to {Binding Path=.}. However it is not equivalent to {Binding Path} as you have typed. If you include the Path property, you must assign it to something, be it Path=. or Path=OtherProperty.

    0 讨论(0)
  • 2020-11-28 09:08

    These are not the same. If you bind this where ConsoleMessages is an ObservableCollection string with just {Binding} you get a "Two-way binding requires Path or XPath." exception where as {Binding Path=.} works. This is with WPF 4.0...

        <ItemsControl x:Name="ConsoleOutput" ItemsSource="{Binding ConsoleMessages, Mode=OneWay}" MaxHeight="400">
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <TextBox Text="{Binding Path=.}" BorderThickness="0" Margin="0" />
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>
    

    My 2p worth...

    0 讨论(0)
  • 2020-11-28 09:10

    The point of the exception presumably is that you cannot two-way bind a binding-source itself, so it tries to prevent you from creating a binding which does not behave the way you would want it to. By using {Binding Path=.} you just trick the error handling.

    (Also it's not unheard of that documentation is erroneous or inaccurate, though i do like the MSDN documentation a lot in general as it usually does contain the crucial points one is interested in)

    0 讨论(0)
提交回复
热议问题