6

As MSDN say:

Optionally, a period (.) path can be used to bind to the current source. For example, Text="{Binding}" is equivalent to Text="{Binding Path=.}".

But in two example below i faced with different behavior:

First:

  <StackPanel>
    <TextBox Text="{Binding Path=MyString, UpdateSourceTrigger=PropertyChanged}"/>
    <Grid DataContext="{Binding Path=MyString}">
      <TextBox Text="{Binding}"></TextBox>
    </Grid>
  </StackPanel>

this example raise exception with message:

"Two-way binding requires Path or XPath."

Second:

  <StackPanel>
    <TextBox Text="{Binding Path=MyString, UpdateSourceTrigger=PropertyChanged}"/>
    <Grid DataContext="{Binding Path=MyString}">
      <TextBox Text="{Binding Path=.}"></TextBox>
    </Grid>
  </StackPanel>

And this example run properly and first TextBox text change reflected to viewmodel and text of first TextBox changed too but when second TextBox text changed that not reflected to viewmodel(or first TextBox)!

Question: I appreciate any one explain this two scenario?

Notice: DataContext of parent control(like window) is a simple class with a Notifiable property MyString:

Thanks.

mkb
  • 1,106
  • 1
  • 18
  • 21
Reza ArabQaeni
  • 4,848
  • 27
  • 46
  • 1
    Editing the text in the second TextBox *replaces* the string instance in the DataContext of the TextBox. It does not update any property. – Clemens May 20 '15 at 07:53
  • @Clemens, "the string instance in the DataContext" is MyString, so why this not updated? – Reza ArabQaeni May 20 '15 at 07:59
  • For the binding error in one case but not the other: the Text property binds two-way by default, and apparently the Binding class checks if the Path property is set when it is two-way. It seems however that it does not check if Path denotes a property or just the source object itself. – Clemens May 20 '15 at 08:01
  • 5
    "the string instance in the DataContext" is MyString. Not exactly, it is just the value of the `MyString` property. A new string value is created when text has been edited. Keep in mind that strings are immutable. – Clemens May 20 '15 at 08:01
  • @Clemens, you right. Please Answer your comments to accept as answer, Of course with more detail, i review several times your comments to understand the gist! – Reza ArabQaeni May 20 '15 at 11:15

1 Answers1

1

seems like whenever there is two way binding {Binding Path=.} is required. try changing the code as:

<StackPanel>
            <TextBox Text="{Binding Path=MyString, UpdateSourceTrigger=PropertyChanged}"/>
            <Grid DataContext="{Binding Path=MyString}">
                <!--<TextBox Text="{Binding}"></TextBox>-->
                <Label Content="{Binding}"/>
            </Grid>
        </StackPanel>

and it works fine. On the original code on way binding also works.

here is a relative topic:

Are "{Binding Path=.}" and "{Binding}" really equal

Community
  • 1
  • 1
Kylo Ren
  • 8,551
  • 6
  • 41
  • 66