开发者

Why is my Binding not working?

This is silverlight code - but I guess that this will be same in WPF - I have this simple classes

public Class A1
{
      string str1;

      public string Str_1
      {
           return str1;
      }
 }

 public Class B1
 {
      A1 a1;

      public A1 A_1
      {
           return a1;
      }
  }

I assume that B1::A1.str1 have the value "my string".

Now in the XAML I have this

<Grid x:Name="LayoutRoot"开发者_Go百科 DataContext="B1">
   <StackPanel> 
      <TextBox Text="{Binding ElementName=A1, Path=Str_1, Mode=TwoWay}"/>
   </StackPanel>
</Grid>

In the the code ( xaml.cs ) i writing in the constructor this

  LayoutRoot.DataContext = this;    

( the B1 object is part of the xaml.cs file and the B1 is also not null and A1 is not null )

But ==> this is not working ... and the text of the textbox is not update with the text that is in A1 object.


You are using element binding but A1 is not a named element in the Xaml page.

You want Text={Binding Path=A_1.Str_1}

This means that it points to the Str_1 property of the A_1 property of the data context (your code behind class).

Please note that TwoWay is pointless here as you have no setters on your properties.

To do this properly (assuming your values will change and be required) you need to implement setters on your A_1 and Str_1 properties and implement INotifyPropertyChanged on both your class A1 & B1.


You can say Text={Binding Path=A_1.Str_1, Mode=TwoWay} I think that should work.

Also if you want to do two-way binding you need to implement INotifyPropertyChanged to let WPF know it has to refresh the UI after you updated the value in code.

GJ


Firstly your class B1 must implement INotifyPropertyChanged like this.

Then you should make a property proxy in your B1 class like this:

public string Str_1
{
    get
    {
        return a1.str1;
    }

    set
    {
        a1.str1 = value;
        this.RaisePropertyChanged("Str_1"); // INotifyPropertyChanged implementation method
    }
}

And finally update your binding:

<TextBox Text="{Binding Path=Str_1}"/>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜