snippetkid
snippetkid

Reputation: 293

Binding to a property value from two different class

In my WPF application, I've two classes, ClassA and ClassB. I have already set the DataContext to ClassA in codebehind

this.DataContext = new ClassA();

So in my XAML I can bind a label content to property Wish of ClassA like below

<Label Name="myLabel" FontSize="40" Content="{Binding Wish}"/>

And this works perfectly fine. But the problem comes when I am trying the same with another class, ClassB. With my this.DataContext = new ClassA(); still staying in the code behind, I am trying to get a property value from ClassB (and yes, ClassB has a property with same name and code) doing like below in my XAML

<StackPanel DataContext="{Binding ClassB}">
            <Label Name="myLabelFromB" FontSize="40" Content="{Binding Wish}"/>
</StackPanel>

in which I'm failing. When I run, the MainWindow just displays the first label only. Why myLabelFromB doesnt get the value of ClassB.Wish even when its parent's DataContext is set to ClassB? Is it possible to achieve the same without modifying my existing code behind?

Upvotes: 3

Views: 6074

Answers (1)

Rohit Vats
Rohit Vats

Reputation: 81233

For that to work, you need to have ClassB property in ClassA somewhat like this:

public class ClassA
{
   public ClassA()
   {
      this.ClassB = new ClassB();
   }

   public string Wish { get; set;}
   public ClassB ClassB { get; set;}
}

Then this will work too :

<StackPanel>
   <Label Name="myLabelFromB" FontSize="40" Content="{Binding ClassB.Wish}"/>
</StackPanel>

Upvotes: 5

Related Questions