I have a ViewModel with an ObservableCollection
, and a View using a Xaml-declared CollectionViewSource
, which is bound to a DataGrid.ItemsSource
.
The ViewModel has a command to create a new object and add it to the ObservableCollection
. Also in the ViewModel, I am handling the CollectionChanged
event, so I "know" when an Add happens.
My doubt is:
how can I make the just-added object selected in the DataGrid?
Notice that the addition and the changed event are all in the ViewModel, but the selection must happen in the View.
I don't mind solutions based on code-behind.
ViewModel:
public class TelaInicialViewModel : ViewModelBase
{
public ObservableCollection<PacienteViewModel> Pacientes { get; set; }
IRepositório<Paciente> _repositório_pacientes = new RepositórioPaciente();
// CONSTRUTOR
public TelaInicialViewModel()
{
var pacientes = _repositório_pacientes.Items.Select(p => new PacienteViewModel(p));
Pacientes = new ObservableCollection<PacienteViewModel>(pacientes);
Pacientes.CollectionChanged += Pacientes_CollectionChanged;
}
void Pacientes_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
switch (e.Action)
{
case NotifyCollectionChangedAction.Add:
foreach (var added in e.NewItems)
{
var p = added as PacienteViewModel;
if (p != null)
{
var novoPaciente = p.GetModel(); ///////// HERE I HAVE IT!!
_repositório_pacientes.Adicionar(novoPaciente);
}
}
break;
case NotifyCollectionChangedAction.Replace:
// ...
break;
}
}
void AdicionarPaciente()
{
var formulárioPaciente = new FormulárioCriaçãoPaciente();
PacienteViewModel novoPaciente = formulárioPaciente.ExibirDiálogo(new Paciente());
if (novoPaciente != null)
//////// HERE I HAVE IT!!!
Pacientes.Add(novoPaciente);
}
public ICommand ComandoAdicionarPaciente { get { return new RelayCommand(AdicionarPaciente); } }
}
View (Xaml)
<UserControl.Resources>
<CollectionViewSource
x:Key="PacientesViewSource"
Source="{Binding Pacientes}"
Filter="PacientesViewSource_Filter"/>
</UserControl.Resources>
<DockPanel>
<DockPanel DockPanel.Dock="Top" Margin="0,10,0,0" >
<TextBox x:Name="FiltroPacienteTextBox" Height="30"
TextChanged="FiltroPacienteTextBox_TextChanged"
DockPanel.Dock="Bottom" Margin="10,10,10,0"/>
<Button x:Name="botaoNovoPaciente" Width="120" Content="Novo"
HorizontalAlignment="Left" Height="30" Margin="10,0,0,0"
Command="{Binding ComandoAdicionarPaciente}"/>
</DockPanel>
<DataGrid x:Name="pacienteDataGrid" Margin="0,10,0,0"
AutoGenerateColumns="False"
CanUserAddRows="False" CanUserDeleteRows="False"
CanUserReorderColumns="False" CanUserResizeRows="False"
ItemsSource="{Binding Source={StaticResource PacientesViewSource}}"
IsSynchronizedWithCurrentItem="True">
</DataGrid>
</DockPanel>