ComboBox selection not updating when model changes
Posted: 28 May 2020, 23:26
I'm trying to get a combobox to work. It seems like it's mostly there: the combo box appears, it shows the correct list of items, and making a change to the combo box updates my data model. However, when I change my datamodel externally from the combo box (in the example below, I explicitly set the TeamId on the player from code), it is not updating the value shown in the combo box.
What I'm trying to do is display a list of players, and next to each player a combobox with a list of possible teams.
My outer xaml looks like this:
The Player_Template looks like this:
And here is what my data model looks like:
Player:
Team:
And the containing model:
I'm a xaml noob, so I'm not sure what I'm doing wrong :(. Any help appreciated.
What I'm trying to do is display a list of players, and next to each player a combobox with a list of possible teams.
My outer xaml looks like this:
Code: Select all
<ItemsControl ItemTemplate="{StaticResource Player_Template}" ItemsSource="{Binding Players}">
</ItemsControl>
Code: Select all
<DataTemplate x:Key="Player_Template">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Name}" HorizontalAlignment="Left" VerticalAlignment="Center" Foreground="#FF87E9FF" Margin="8,0,0,0" TextAlignment="Left" FontFamily="Arial" FontWeight="Bold" FontSize="16" />
<ComboBox x:Name="TeamSelector" HorizontalAlignment="Left" VerticalAlignment="Center" Margin="0,0,8,0"
ItemsSource="{Binding RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}, Path=DataContext.Teams}"
SelectedValue="{Binding TeamId, Mode=TwoWay}"
SelectedValuePath="Id"
ItemTemplate="{StaticResource TeamOptionTemplate}"/>
</StackPanel>
</DataTemplate>
Player:
Code: Select all
public class Player : NotifyPropertyChangedBase
{
public string _name;
public string Name
{
get { return _name; }
set { SetStringProperty(ref _name, value); }
}
public int _teamId;
public int TeamId
{
get { return _teamId; }
set { SetIntProperty(ref _teamId, value); }
}
}
Code: Select all
public class Team : NotifyPropertyChangedBase
{
public string _name;
public string Name
{
get { return _name; }
set { SetStringProperty(ref _name, value); }
}
public int _id;
public int Id
{
get { return _id; }
set { SetIntProperty(ref _id, value); }
}
}
Code: Select all
public class TeamModel : NotifyPropertyChangedBase
{
public ObservableCollection<Team> Teams { get; set; }
public ObservableCollection<Player> Players { get; set; }
}