gpt4 book ai didi

c# - 在 WPF 中使用 ICommand——返回 null 的命令

转载 作者:太空宇宙 更新时间:2023-11-03 18:35:32 25 4
gpt4 key购买 nike

我正在 WPF 中处理一个示例 ViewModel,我目前将 View 中的 3 个文本框绑定(bind)到 IdFirstNameLastName .然后,我在 xaml.cs 文件中有一个按钮单击事件,该事件执行更新示例数据库表的方法。我正在尝试围绕 MVVM 和 WPF 进行思考。我想取消按钮单击事件并改为绑定(bind)到命令。我正在使用 Linq to Sql 进行数据库连接。

当我调试代码时,一切都返回 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();
}
}

在 VM 中,这是我正在尝试使用的命令

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);
}

是的,我把点击事件去掉,换成了

<Button Command="{Binding Path=UserUpdate}"/>

我是这样绑定(bind)文本框的

<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}"/>

最佳答案

命令旨在替换按钮的Click 事件处理程序。

您应该删除事件处理程序并执行

<Button Command="{Binding UserUpdate}"/>

关于c# - 在 WPF 中使用 ICommand——返回 null 的命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16027820/

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