我正在研究WPF中的示例ViewModel,並且我正在將視圖中的3個文本框綁定到Id
,FirstName
和LastName
。然後,我在xaml.cs文件中有一個按鈕單擊事件,該文件執行更新示例數據庫表的方法。我正試圖圍繞MVVM和WPF進行包裝。我想取消按鈕單擊事件並將其綁定到Command。我正在使用Linq to Sql進行數據庫連接。在WPF中利用ICommand - 命令返回null
當我調試代碼時,一切都返回null。我在正確的道路上嗎?
謝謝!
這裏是VM的部分(我沒有要發佈的所有代碼。)
public class People
{
public Guid Id {get; set;}
public string FirstName {get; set;}
public string LastName {get; set;}
}
private People mPeople = null;
private Guid mId = Guid.empty;
public People people
{
get {return mPeople;}
set {mPeople = value; OnPropertyChanged("people");}
}
public overide void Refresh()
{
Using (DatabaseDataContext dc = new DatabaseDataContext())
{
mId = CurrentUser.Identity;
var query = from person in dc.PeopleTables
where person.PId = mId
select new People()
{
Id = person.PId,
FirstName = person.FirstName,
LastName = person.LastName
};
mPeople = query.First();
}
}
在這裏的虛擬機就是我用命令
private RelayCommand mUserUpdate = null;
public ICommand UserUpdate
{
get
{
if(mUserUpdate == null) mUserUpdate = new RelayCommand(p => UpdateUser(p));
return mUserUpdate;
}
}
private void UpdateUser(object parameter)
{
People pe = parameter as People;
UpdateUser(pe.Id, pe.FirstName, pe.LastName);
}
public static void UpdateUser(Guid Id, string FirstName, string LastName)
{
DatabaseDataContext DC = new DatabaseDatacontext();
var User = (from c in DC.GetTable<PeopleTable>()
where c.PId = mId
select c).SingleOrDefault();
if (User == null
{
//Do my inserts here
}
else
{
try
{
User.Id = Id;
User.FirstName = FirstName;
User.LastName = LastName;
DC.SubmitChanges();
}
catch
{
throw ex;
}
}
}
想這是我的單擊事件我用
private void btnSave_Click(object sender, RoutedEventArgs e)
{
UserViewModel.UpdateUser(txtId.Text, txtFirstName.Text, txtLastName.Text);
}
是啊,我拿出click事件,並與
<Button Command="{Binding Path=UserUpdate}"/>
我綁定文本框這樣
<TextBox Width="250" Text="{Binding Path=Id}"/>
</StackPanel>
<StackPanel Orientation="Horizontal" Margin="0,5,0,0">
<Label Content="First Name:" Margin="0,0,4,0"/>
<TextBox Width="250" Text="{Binding Path=FirstName}"/>
</StackPanel>
<StackPanel Orientation="Horizontal" Margin="0,5,0,0">
<Label Content="Last Name:" Margin="35,0,4,0"/>
<TextBox Width="250" Text="{Binding Path=LastName}"/>
我們可以看到您的XAML代碼試試這個?特別是您在按鈕上設置Command屬性的部分。 – Julien