code snippet:
xaml
<TextBlock Grid.Row="0" Text="{Binding Path=NodeType}"></TextBlock>
<Button Name="bt" Grid.Row="1" Click="bt_Click">click</Button>
c#
public FamilyMemberInfo MemberInfo;
public MainWindow()
{
InitializeComponent();
MemberInfo = new FamilyMemberInfo();
MemberInfo.NodeType = "aa";
this.DataContext = MemberInfo;
}
private void bt_Click(object sender, RoutedEventArgs e)
{
//MemberInfo.NodeType = "bb";
FamilyMemberInfo mi2 = new FamilyMemberInfo();
mi2.NodeType = "bb";
MemberInfo = mi2;
}
If I change the NodeType to ‘bb’, the textblock is changed too, but if I create a bland new object and set the property NodeType to ‘bb’, then assign it to MemberInfo, the textblock is not updated. could anyone explain that for me? thanks in advance.
And say that the class ‘FamilyMemberInfo’ has 20 properties, all are binding with elements(textblock, combobox, etc) on the UI, and I get an instance of FamilyMemberInfo from some other place, I want to simply assign it to the MemberInfo as code above to make the UI update accordingly, how to make it work?
Thanks.
You have to set
DataContextto the new instance you created.The reason is when you set
this.DataContext = MemberInfo;inside the constructor, it points to the object you created in the constructor, let’s name it objectA.Now you set
MemberInfo = mi2,mi2is a difference object and you setMemberInfoto point tomiwhile objectAthat you created (inside the constructor) is still there andthis.DataContextis still point to that object.So, you have to set
DataContextto point to the new object as in above code.