我想将三个文本框绑定(bind)到结构的三个成员。这是我的 XAML 代码:
<TextBox Grid.Column="1" Height="32" HorizontalAlignment="Left" Margin="322,12,0,0" Text="{Binding SelectedStudentDetails.FirstName, Mode=TwoWay}" TextWrapping="Wrap" VerticalAlignment="Top" Width="199" />
<TextBox Grid.Column="1" Height="30" HorizontalAlignment="Left" Margin="322,75,0,0" Text="{Binding SelectedStudentDetails.LastName,Mode=TwoWay}" TextWrapping="Wrap" VerticalAlignment="Top" Width="199" />
<TextBox Grid.Column="1" Height="33" HorizontalAlignment="Left" Margin="322,137,0,0" Text="{Binding SelectedStudentDetails.City,Mode=TwoWay}" TextWrapping="Wrap" VerticalAlignment="Top" Width="199" />
这是 viewModel 片段:
private Student _selectedstudentDetails;
public Student SelectedStudentDetails
{
get {
return _selectedstudentDetails;
}
set
{
if (_selectedstudentDetails != value)
{
_selectedstudentDetails = value;
RaisePropertyChanged("SelectedStudentDetails");
}
}
}
//StudentList is the observable list type
public void AddStudentDetails(object param)
{
StudentList.Add(new Student { FirstName = SelectedStudentDetails.FirstName, LastName = SelectedStudentDetails.LastName, City = SelectedStudentDetails.City });
}
如何使用带有文本框控件的绑定(bind)结构填充 Student 对象?
学生类(class)声明:
namespace SimplestMVVM.Model
{
public class Student
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string City { get; set; }
}
}
最佳答案
好吧,您的问题不是很清楚,但我想您的问题是 SelectedStudentDetails.FirstName、SelectedStudentDetails.LastName 和 SelectedStudentDetails.City 始终为空,对吗?
基本上这是因为您的学生对象必须是一个 View 模型(或至少是 INotifyPropertyChanged)。因为它必须在您从 View 中更新其属性时通知。 (是的,它必须是属性)。否则,它永远不会通知您更改值,并且它们保持为空。
在我看来,最简单的方法是创建一个具有所需属性的 CLASS StudentViewModel。这样你的绑定(bind)就可以工作了。
另一种解决方案(但老实说,我没有看到任何好的理由这样做,它仍然应该工作)可能是直接将您的 Student 转换为 INotifyPropertyChanged 类。
我在这里的免费提示,如果您滥用 margin ,在您的 XAML 中会更好。你可以做这样的事情:
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<TextBox Grid.Column="0" Height="30" HorizontalAlignment="Left" Text="{Binding SelectedStudentDetails.FirstName, Mode=TwoWay}" TextWrapping="Wrap" VerticalAlignment="Top" Width="199" />
<TextBox Grid.Column="1" Height="30" HorizontalAlignment="Left" Text="{Binding SelectedStudentDetails.LastName,Mode=TwoWay}" TextWrapping="Wrap" VerticalAlignment="Top" Width="199" />
<TextBox Grid.Column="2" Height="30" HorizontalAlignment="Left" Text="{Binding SelectedStudentDetails.City, Mode=TwoWay}" TextWrapping="Wrap" VerticalAlignment="Top" Width="199" />
</Grid>
关于c# - 如何在 WPF MVVM 方法中将结构绑定(bind)到文本框控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25744238/