[英]How to bind a structure to textbox control in WPF MVVM approach
我想將三個文本框綁定到結構的三個成員。 這是我的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 });
}
如何使用帶有文本框控件的綁定結構來填充Student對象?
學生班聲明:
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始終為空,對嗎?
基本上這是因為您的Student對象必須是viewModel(或者至少是INotifyPropertyChanged)。 因為它必須在您從視圖更新其屬性時通知。 (是的,它必須是屬性)。 否則,它永遠不會通知您更改值,並且它們保持為空。
在我的觀點中,最簡單的方法是使用所需屬性創建CLASS StudentViewModel。 這樣,綁定將起作用。
另一個解決方案(但老實說,我看不出有什么充分的理由這樣做,但仍然應該可行)可以是直接將您的Student轉換為INotifyPropertyChanged類。
就像我在這里的免費提示,如果您濫用保證金,那么在您的XAML中會更好。 Youd可以做這樣的事情:
<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>
為您的學生類實施INotifyPropertyChanged
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.