I am new to WFP and I am stuck with data binding.
On my first user control I have 2 texboxes and on my second user control I have 2 labels. And I have a class holding the properties.
My question is how can I link these two user control to the same class ? The problem here is that each user control seem to point on a different instance of the same class.
I have also attached 2 pictures as a visual example of my problem
My first user control code:
<UserControl.DataContext>
<local:Players/>
</UserControl.DataContext>
<!--Display Players Name-->
<Label Name="LabelPlayer1Name" Grid.Row="1" Grid.Column="0"
Content="{Binding Player1Name}"
/>
<Label Grid.Row="1" Grid.Column="1" Content="VS" Foreground="#e74c3c"/>
<Label Name="LabelPlayer2Name"
Grid.Row="1" Grid.Column="2"
Content="{Binding Player2Name}"
/>
<!--Input Players Name-->
<TextBox x:Name="TextBoxPlayer1Name" Grid.Column="0" Grid.Row="2" Text="{Binding Player1Name,
UpdateSourceTrigger=PropertyChanged}"
KeyDown="TextBoxPlayer1Name_KeyDown"
/>
<TextBox x:Name="TextBoxPlayer2Name" Grid.Column="2" Grid.Row="2" Text="{Binding Player2Name,
UpdateSourceTrigger=PropertyChanged}"
KeyDown="TextBoxPlayer2Name_KeyDown"
/>
My second user control code:
<UserControl.DataContext>
<local:Players/>
</UserControl.DataContext>
<Label Grid.Column="0" Grid.Row="0" Content="{Binding Player1Name}"/>
<Label Grid.Column="2" Grid.Row="0" Content="{Binding Player2Name}"/>
Player Class:
public class Players : INotifyPropertyChanged
{
#region PlayersName field
private string _player1Name;
private string _player2Name;
public string Player1Name
{
get { return _player1Name; }
set
{
_player1Name = value;
OnPropertyChanged();
}
}
public string Player2Name
{
get { return _player2Name; }
set
{
_player2Name = value;
OnPropertyChanged();
}
}
#endregion
#region ctor
public Players()
{
_player1Name = "Player1";
_player2Name = "Player2";
}
#endregion
#region On Property Changed
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
}
first user control: User control 1 second user control: User control 2
in this example, the first user control is used to set Player1Name and Player2Name in the Player class. But the second user control is displaying something else