Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why this type binding has strange behavior?

Tags:

c#

binding

wpf

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.

like image 207
Reza ArabQaeni Avatar asked May 20 '15 07:05

Reza ArabQaeni


1 Answers

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

like image 176
Kylo Ren Avatar answered Oct 25 '22 00:10

Kylo Ren