如何在WPF中重新加载(重置)整个页面?
我有Request.xaml
按钮和许多comboxes,所以我想重新加载它并将combox值置于按钮点击后将其设置为默认值。 我当然会做更多的工作人员。
我的Request.xaml
代码包含以下部分代码:
另外,xaml代码这样的事件
而Request.xaml.cs
文件只有private void Button_Click(object sender, RoutedEventArgs e)
函数。
我以这种方式显示Request.xaml
:首先, MainWindow.xaml
显示MainPage.xaml
, ,最后是
MainPage.xaml
dispays Request.xaml
是否可以重置整个页面,因为我需要让用户有机会将新请求的参数添加到现有参数中,最终将位于.xml
文件中?
也许可以通过OnNavigatedTo方法或UIElement.InvalidateVisual方法实现 ( http://msdn.microsoft.com/en-us/library/system.windows.uielement.invalidatevisual.aspx )
当然有可能! 但是……你是否将combobox数据绑定到一些底层对象实例?
然后你可以轻松地以“硬”方式进行设置
page.DataContext = null; page.DataContext = new Foo();
然后将使用“默认”值重新初始化所有数据绑定。
到目前为止,我不使用MVVM / DataContext,因此在特定情况下,只有一种方法可以将值设置为默认值,而是手动执行。
TxtBlock_numRequest.Text = "Default";
但这个解决方案看起来非常糟糕,但至少它可行。
解决此问题的另一种方法是使用MVVM和DataBinding。 该解决方案由@ZeroART提供:
//XAML // // //ViewModel public class MainViewModel : INotifyPropertyChanged { private IList _items; private bool _canExecute; private ICommand _clickCommand; private string _textValue; private string _selectedValue; public IList Items { get { return _items; } } public string SelectedValue { get { return _selectedValue; } set { _selectedValue = value; OnPropertyChanged("SelectedValue"); } } public string TextValue { get { return _textValue; } set { _textValue = value; OnPropertyChanged("TextValue");} } public void Save() { SelectedValue = _items.FirstOrDefault(); TextValue = "Значение по умолчанию"; } public ICommand ClickCommand { get { return _clickCommand ?? (new RelayCommand(() => Save(), _canExecute)); } } public MainViewModel() { _items = new List { "Test1", "Test2", "Test3" }; _selectedValue = _items.First(); _textValue = "Значение по умолчанию"; _canExecute = true; } public event PropertyChangedEventHandler PropertyChanged; public void OnPropertyChanged(string propertyName) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } } public class RelayCommand : ICommand { private Action _action; private bool _canExecute; public RelayCommand(Action action, bool canExecute) { _action = action; _canExecute = canExecute; } public bool CanExecute(object parameter) { return _canExecute; } public event EventHandler CanExecuteChanged; public void Execute(object parameter) { _action(); } }
另外我们需要这个:
private readonly MainViewModel _viewModel; public MainWindow() { InitializeComponent(); _viewModel = new MainViewModel(); this.DataContext = _viewModel; }