0
votes

i know that was asked many times before, but i cant find my error, why it dont work. I set they DataContext in Xaml. Would it be better in de Code behind? I want to Display A ObservableCollection in an DataGrid, where i can select multiple Rows, which I get back to my viewmodel. ViewModel:

public class MainWindowViewModel : INotifyPropertyChanged
{
    public ObservableCollection<Projekt> Projekts { get; set; }

    private string _name;

    public string Name
    {
        get { return _name; }
        set
        {
            _name = value;
            NotifyPropertyChanged();
        }
    }
    private string _bez;

    public string Bezeichnung
    {
        get { return _bez; }
        set
        {
            _bez = value;
            NotifyPropertyChanged();
        }
    }
    private string _number;

    public string Nummer
    {
        get { return _number; }
        set
        {
            _number = value;
            NotifyPropertyChanged();
        }
    }




}

Xaml:

 <Window.DataContext>
    <kbwViewModels:MainWindowViewModel/>
</Window.DataContext>
<Grid>
    <DataGrid x:Name="dg_Projekt" HorizontalAlignment="Left" Height="238" Margin="10,52,0,0" VerticalAlignment="Top" Width="425" SelectionMode="Extended" BorderBrush="White" Background="Gray" ItemsSource="{Binding Projekts}" 
        SelectionUnit="FullRow">
        <DataGrid.Columns>
            <DataGridTextColumn Header="Nummer" Binding="{Binding Nummer}" FontFamily="Arial"/>
            <DataGridTextColumn Header="Projekt Name" Binding="{Binding Bezeichnung}" FontFamily="Arial" />
            <DataGridTextColumn Header="Status"  Binding="{Binding Status}" FontFamily="Arial"/>
        </DataGrid.Columns>
    </DataGrid>
</Grid>

MainWindow:

private Common common;

    private MainWindowViewModel viewModel;

    public MainWindow()
    {

        InitializeComponent();

        string connectionDb = ConfigurationManager.ConnectionStrings["KBWTime"].ConnectionString;
        common = new Common(connectionDb);
        viewModel = new MainWindowViewModel();  
        viewModel.Projekts = new ObservableCollection<Projekt>(common.GetProjektList());

    }
1

1 Answers

0
votes

ObservableCollection only emits an event when the collection changes (new element, remove element, etc.). However you are change a collection with other here:

viewModel.Projekts = new ObservableCollection<Projekt>(common.GetProjektList());

So you have two options: A) Add each item to the ObservableCollection

foreach(var item in common.GetProjektList())
   viewModel.Projekts.Add(item);

B) Create a setter for Projekts, and notify when this property changes