【发布时间】:2017-09-08 04:02:31
【问题描述】:
我正在尝试了解 Prism 和 Unity 如何在 WPF 中工作,但目前被一项简单的任务所阻碍。可能我对它的工作原理有误解。
如何刷新绑定的视图模型?
我有一个使用 Prisms RegionManager 加载用户控件的 wpf 应用程序:
<ContentControl Grid.Row="1" prism:RegionManager.RegionName="ContentRegion" x:Name="mainContent" HorizontalAlignment="Center" Margin="0,25,0,0"/>
在我的用户控件中,我有一个字段供用户使用提交按钮和清除按钮填写(缩写的用户控件内容)
<TextBox Margin="10,3,15,0" Text="{Binding LastName, UpdateSourceTrigger=PropertyChanged}" MinWidth="150" materialDesign:HintAssist.Hint="*Last Name" Style="{StaticResource MaterialDesignFloatingHintTextBox}" FontSize="16"/>
<Button Command="{Binding ClearCommand}" Style="{StaticResource MaterialDesignRaisedAccentButton}" Margin="0 12 8 0" Width="155" ToolTip="Discard information entered and reset form" Background="#FF990B0B" Foreground="#FFECE9E9" BorderBrush="DarkRed">Cancel and Discard</Button>
我的字段绑定效果很好,我已将我的按钮绑定到一个命令,该命令将调用我想要重置表单的方法:
public class CheckInViewModel : BindableBase
{
private IEventAggregator _eventAggregator;
private string _lastName;
public string LastName
{
get { return _lastName; }
set { SetProperty(ref _lastName, value); }
}
public DelegateCommand ClearCommand { get; set; }
private void ExecuteClear()
{
//reset form here
}
public CheckInViewModel(IEventAggregator eventAggregator)
{
_eventAggregator = eventAggregator;
ClearCommand = new DelegateCommand(ExecuteClear);
}
}
我知道我可能只是在 ExecuteClear 方法中手动重置所有字段,但这似乎有点笨拙且容易出错,因为实际上我有 40 多个字段要处理。
我尝试将绑定的字段移动到一个完全独立的模型,然后将该模型作为我的视图模型的属性,以便我可以在 clear 方法中重新实例化它,但这样做时似乎不会更新视图。我想我一定是错过了一个方法调用来取消绑定我的最后一个模型并重新绑定到新模型,但我不知道该怎么做,也找不到任何这样做的文档。
失败尝试示例:
public class CheckInViewModel : BindableBase
{
private IEventAggregator _eventAggregator;
public CheckInModel checkInModel { get; set; }
public DelegateCommand ClearCommand { get; set; }
private void ExecuteClear()
{
checkInModel = new CheckInModel();
}
public CheckInViewModel(IEventAggregator eventAggregator)
{
checkInModel = new CheckInModel();
_eventAggregator = eventAggregator;
ClearCommand = new DelegateCommand(ExecuteClear);
}
}
public class CheckInModel : BindableBase
{
private string _lastName
public string LastName
{
get { return _lastName; }
set { SetProperty(ref _lastName, value); }
}
}
<TextBox Margin="10,3,15,0" Text="{Binding checkInModel.LastName, UpdateSourceTrigger=PropertyChanged}" MinWidth="150" materialDesign:HintAssist.Hint="*Last Name" Style="{StaticResource MaterialDesignFloatingHintTextBox}" FontSize="16"/>
<Button Command="{Binding ClearCommand}" Style="{StaticResource MaterialDesignRaisedAccentButton}" Margin="0 12 8 0" Width="155" ToolTip="Discard information entered and reset form" Background="#FF990B0B" Foreground="#FFECE9E9" BorderBrush="DarkRed">Cancel and Discard</Button>
【问题讨论】: