1
votes

I'm new to WPF, I am using MVVM via MVVMLight, I have a datagrid bound to a ObservableCollection of view models, When I manually update modelView, the view is changed as expected, the problem is that when I change view, the viewModel's value is not changed,

this is model:

public class Student
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

this is viewModel:

public class StudentViewModel : ViewModelBase
{
    private Student _student;

    public StudentViewModel(Student student)
    {
        _student = student;
    }

    public string FirstName
    {
        get { return _student.FirstName; }
        set
        {
            if(_student.FirstName==value)return;
            _student.FirstName = value;
            RaisePropertyChanged("FirstName");
        }
    }

    public string LastName
    {
        get { return _student.LastName; }
        set
        {
            if(_student.LastName==value)return;
            _student.LastName = value;
            RaisePropertyChanged("LastName");
        }
    }
}

this is Test.xaml:

<DataGrid Name="DgrdColumns" Grid.Row="1" Grid.Column="0" AutoGenerateColumns="False">
        <DataGrid.Columns>
            <DataGridTemplateColumn Header="FirstName">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <TextBox Text="{Binding FirstName, Mode=TwoWay}"></TextBox>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>

            <DataGridTemplateColumn Header="LastName" Width="150">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <TextBox Text="{Binding LastName, Mode=TwoWay}"></TextBox>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
        </DataGrid.Columns>
    </DataGrid>

this is bind data code:

void BindData()
    {
        var students = new List<Student>()
        {
            new Student()
            {
                FirstName = "aa",
                LastName = "AA"
            },
            new Student()
            {
                FirstName = "bb",
                LastName = "BB"
            }
        };

        var viewModels=new ObservableCollection<StudentViewModel>(students.Select(x=>new StudentViewModel(x)));
        DgrdColumns.ItemsSource = viewModels;
    }
1
What does "that when I change view" mean ?Henk Holterman
means I edit students in the windowCodisan

1 Answers

0
votes

Please try to set UpdateSourceTrigger in your bindings:

<TextBox Text="{Binding FirstName, Mode=TwoWay, UpdateSourceTrigger=LostFocus}" />

Let me know if it still doesn't work.