我有一个prism unity应用程序,如何在viewmodel属性中更改一个子类?
如何在viewmodel中实现具有复杂对象的CanExecute?
MODEL
public class WardModel : BindableBase
{
private string _Id;
public string Id
{
get { return _Id; }
set { SetProperty(ref _Id, value); }
}
}
视图模型
public class ucAddViewModel : BindableBase
{
private readonly IUnityContainer _unityContainer;
private readonly IRegionManager _regionManager;
private WardModel _Ward;
public WardModel Ward
{
get
{
return _Ward;
}
set
{
SetProperty(ref _Ward, value);
CanSaveExecute = Ward.Id != null && Ward.Id != string.Empty;
}
}
}
XAML
<TextBox Text="{Binding Ward.Id, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Height="30" VerticalAlignment="Top" Margin="0,0,0,10"></TextBox>
答案 0 :(得分:0)
Execute和CanExecute方法与命令一起使用,不能在访问器中使用它们。 如果您想确保您的Id没有错误的值,只需将您的验证规则放入Model类。
public class WardModel : BindableBase
{
private string _Id;
public string Id
{
get { return _Id; }
set
{
if(!string.IsNullOrWhiteSpace(value)) SetProperty(ref _Id, value);
}
}
}
答案 1 :(得分:0)
假设您想在viewModel的属性发生更改后刷新命令。
型号:
public class MyModel : BindableBase
{
private string Name _name;
public Name
{
get { return _name; }
set { SetProperty(ref _name, value); }
}
}
视图模型:
public class MyViewModel : BindableBase
{
private DelegateCommand _myCommand;
public DelegateCommand MyCommand => _myCommand ?? (_myCommand = new DelegateCommand(Execute, CanExecute));
//your method that will be executed
private void Execute()
{
//Do sth.
}
//will be triggered through MyCommand.RaiseCanExecuteChanged()
private bool CanExecute()
{
//you validating logic, e.g.
return MyComplexObject != null;
}
private MyModel _myComplexObject;
public MyModel MyComplexObject
{
get { return _myComplexObject; }
set
{
SetProperty(ref _myComplexObject, value);
//Trigger the CanExecuteChanged Event
MyCommand.RaiseCanExecuteChanged();
}
}
}