gpt4 book ai didi

mvvm datagrid 无法从 View 更新模型

转载 作者:行者123 更新时间:2023-12-03 10:46:28 25 4
gpt4 key购买 nike

我是 WPF 新手,我正在通过 MVVMLight 使用 MVVM,我有一个绑定(bind)到 View 模型的 ObservableCollection 的数据网格,当我手动更新 modelView 时, View 会按预期更改,
问题是当我改变 View 时,viewModel 的值没有改变 ,

这是模型:

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

这是 View 模型:
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");
}
}
}

这是 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>

这是绑定(bind)数据代码:
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;
}

最佳答案

请尝试设置UpdateSourceTrigger在您的绑定(bind)中:

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

让我知道它是否仍然不起作用。

关于mvvm datagrid 无法从 View 更新模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24218178/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com