Xaml 使用命令传递对象
Xaml pass object with command
假设我有 class 看起来像这样:
public class User
{
public string Name { get; set; }
public int Age { get; set; }
}
用户是我在视图中使用的视图模型的一部分,我尝试像这样更新它的属性:
<TextBox Text="{Binding User.Name}"></TextBox>
<TextBox Text="{Binding User.Age, mode=two-way, updatesourcetrigger = onpropertychanged}"></TextBox>
<Button Content="Save user" Command="{Binding SaveUserCommand}" CommandParameter="{Binding User}" />
这是视图模型:
public RelayCommand<User> SaveUserCommand { get; private set; }
public MainViewModel()
{
SaveUserCommand = new RelayCommand<User>(SaveUser);
}
public void SaveUser(User user)
{
//logic for saving user
}
我认为这会让我更改文本框中的值,然后将用户传递给视图模型。问题是什么都没有发送,SaveUser()
被 null 触发。
有人能看出我是什么吗missing/missunderstanding?
谢谢!
编辑:
这是在视图中代表我的用户的 属性:
private User _user;
public User User
{
get
{
return _user;
}
set
{
if (_user != value)
{
_user = value;
RaisePropertyChanged("User");
}
}
}
您 TextBox
控件上的 Bindings
需要 Mode=TwoWay
。 TextBox
控件也只更新 LostFocus
上的源值,因此您可能还想用 Binding
上的 UpdateSourceTrigger=PropertyChanged
更改它。
您的 ViewModel
似乎还缺少 public 属性 User
。
你需要:
public User User {get;set;}
...根据您当前的 Binding
定义。
我也看不到 ViewModel class 的定义,但它应该实现 INotifyPropertyChanged
(或者基础 class 应该实现它)。
编辑:
OP 没有实例化 User
属性.
假设我有 class 看起来像这样:
public class User
{
public string Name { get; set; }
public int Age { get; set; }
}
用户是我在视图中使用的视图模型的一部分,我尝试像这样更新它的属性:
<TextBox Text="{Binding User.Name}"></TextBox>
<TextBox Text="{Binding User.Age, mode=two-way, updatesourcetrigger = onpropertychanged}"></TextBox>
<Button Content="Save user" Command="{Binding SaveUserCommand}" CommandParameter="{Binding User}" />
这是视图模型:
public RelayCommand<User> SaveUserCommand { get; private set; }
public MainViewModel()
{
SaveUserCommand = new RelayCommand<User>(SaveUser);
}
public void SaveUser(User user)
{
//logic for saving user
}
我认为这会让我更改文本框中的值,然后将用户传递给视图模型。问题是什么都没有发送,SaveUser()
被 null 触发。
有人能看出我是什么吗missing/missunderstanding? 谢谢!
编辑:
这是在视图中代表我的用户的 属性:
private User _user;
public User User
{
get
{
return _user;
}
set
{
if (_user != value)
{
_user = value;
RaisePropertyChanged("User");
}
}
}
您 TextBox
控件上的 Bindings
需要 Mode=TwoWay
。 TextBox
控件也只更新 LostFocus
上的源值,因此您可能还想用 Binding
上的 UpdateSourceTrigger=PropertyChanged
更改它。
您的 ViewModel
似乎还缺少 public 属性 User
。
你需要:
public User User {get;set;}
...根据您当前的 Binding
定义。
我也看不到 ViewModel class 的定义,但它应该实现 INotifyPropertyChanged
(或者基础 class 应该实现它)。
编辑:
OP 没有实例化 User
属性.