[WPF] 在 ViewModel 中讓數據驗證出錯(Validation.HasError)的控制項獲得焦點
1. 需求
在 MVVM 中 ViewModel 和 View 之間的交互通常都是靠 Icommand 和 INotifyPropertyChanged,不過有時候還會需要從 MVVM 中控制 View 中的某個元素,讓它獲得焦點,例如這樣:
上面的 gif 是我在另一篇文章 《自定義一個「傳統」的 Validation.ErrorTemplate》 中的一個示例,在這個示例中我修改了 Validation.ErrorTemplate
,這樣在數據驗證出錯後,相關的控制項會顯示一個紅色的框,獲得焦點後用 Popup 彈出具體的錯誤資訊。可是這個過程稍微不夠流暢,我希望點擊 Sign In 按鈕後,數據驗證錯誤的控制項自動獲得焦點,像下面這個 gif 那樣:
這個需求在使用 CodeBehind 的場景很容易實現,但 MVVM 模式就有點難,因為 ViewModel 應該不能直接調用 View 上的任何元素的函數。 如果可以的話,最好通過 ViewModel 上的屬性控制 UI 元素,讓這個 UI 元素獲得焦點。
這篇文章介紹了兩種方式實現這個需求。
2. 環境
首先介紹這個例子使用到的 ViewModel 和 View。
首先在 Nuget 上安裝 Prism.Core,然後實現一個簡單的 ViewModel,這個 ViewModel 只有一個 Name 屬性和一個 SubmitCommand:
public class ViewModel : ModelBase
{
public string Name { get; set; }
public ICommand SubmitCommand { get; }
public ViewModel()
{
SubmitCommand = new DelegateCommand(Submit);
}
private void Submit()
{
ErrorsContainer.ClearErrors();
if (string.IsNullOrEmpty(Name))
ErrorsContainer.SetErrors(nameof(Name), new List<string> { "請輸入名稱" });
}
}
public abstract class ModelBase : BindableBase, INotifyDataErrorInfo
{
private ErrorsContainer<string> _errorsContainer;
public bool HasErrors => ErrorsContainer.HasErrors;
public ErrorsContainer<string> ErrorsContainer
{
get
{
if (_errorsContainer == null)
{
_errorsContainer =
new ErrorsContainer<string>(pn => RaiseErrorsChanged(pn));
}
return _errorsContainer;
}
}
public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged;
public IEnumerable GetErrors(string propertyName)
{
return ErrorsContainer.GetErrors(propertyName);
}
protected void RaiseErrorsChanged(string propertyName)
{
ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(propertyName));
}
}
View 上自定義一個 ErrorTemplate
,還有一個綁定到 Name 的 TextBox,一個綁定到 SubmitCommand 的 Button:
<Grid HorizontalAlignment="Center" VerticalAlignment="Center" Width="300">
<Grid.Resources>
<ControlTemplate x:Key="ErrorTemplate">
<AdornedElementPlaceholder>
<kino:ValidationContent />
</AdornedElementPlaceholder>
</ControlTemplate>
<Style TargetType="Control">
<Setter Property="Margin" Value="5" />
<Setter Property="FontSize" Value="15" />
<Setter Property="Validation.ErrorTemplate" Value="{StaticResource ErrorTemplate}" />
</Style>
<Style TargetType="Button" BasedOn="{StaticResource {x:Type Control}}"/>
</Grid.Resources>
<StackPanel>
<TextBox x:Name="AddressTextBox"/>
<TextBox x:Name="NameTextBox" Text="{Binding Name,Mode=TwoWay}"/>
<Button Content="Submit" Margin="5" Command="{Binding SubmitCommand}"/>
</StackPanel>
</Grid>
3. FocusManager.FocusedElement 附加屬性使用屬性控制焦點
ViewModel 不能直接控制 UI 元素的行為,但它可以通過屬性影響 UI 元素的某些屬性,例如將 Control 的 IsEnabled 與 ViewModel 上的屬性綁定。WPF 可用於控制焦點的屬性是 FocusManager.FocusedElement 附加屬性,這個屬性用於獲取和設置指定焦點範圍內的聚焦元素。一般使用方法如下,這段程式碼將 Button 設置為焦點元素:
<StackPanel FocusManager.FocusedElement="{Binding ElementName=firstButton}">
<Button Name="firstButton" />
</StackPanel>
4. 使用屬性控制焦點
了解 FocusManager.FocusedElement 的使用方式以後,我們可以在 ViewModel 中定義一個 bool 類型屬性 IsNameHasFocus
,當調用 Submit 函數時更改這個屬性值以控制 UI 焦點。
private bool _isNameHasFocus;
public bool IsNameHasFocus
{
get => _isNameHasFocus;
set => SetProperty(ref _isNameHasFocus, value);
}
private void Submit()
{
IsNameHasFocus = false;
ErrorsContainer.ClearErrors();
if (string.IsNullOrEmpty(Name))
{
ErrorsContainer.SetErrors(nameof(Name), new List<string> { "請輸入名稱" });
IsNameHasFocus = true;
}
}
在 XAML 中定義一個 StackPanel 的樣式並為它添加 DataTrigger
,當 IsNameHasFocus 的值為 True 時,通過 FocusManager.FocusedElement
指定某個元素獲得焦點:
<StackPanel.Style>
<Style>
<Style.Triggers>
<DataTrigger Binding="{Binding IsNameHasFocus}" Value="True">
<Setter Property="FocusManager.FocusedElement" Value="{Binding ElementName=NameTextBox}"/>
</DataTrigger>
</Style.Triggers>
</Style>
</StackPanel.Style>
5. 自動獲得焦點
上面的做法實現了我的需求,而且使用這種方案可以讓 ViewModel 對 View 有更多的控制權,可以指定哪個 UI 元素在任何時間獲得焦點,但壞處就是要寫很多程式碼,而且屬性越多耦合越多。
另一種做法是讓 Validation.HasError 為 true 的控制項自動獲得焦點,可以在 View 上添加這個樣式:
<Style TargetType="TextBox" BasedOn="{StaticResource {x:Type Control}}">
<Style.Triggers>
<DataTrigger Binding="{Binding (Validation.HasError),RelativeSource={RelativeSource Mode=Self}}" Value="True">
<Setter Property="FocusManager.FocusedElement" Value="{Binding RelativeSource={RelativeSource Mode=Self}}"/>
</DataTrigger>
</Style.Triggers>
</Style>
ViewModel 中可以不負責處理焦點,只負責驗證數據:
private void Submit()
{
ErrorsContainer.ClearErrors();
if (string.IsNullOrEmpty(Name))
ErrorsContainer.SetErrors(nameof(Name), new List<string> { "請輸入名稱" });
}
這個全局 Style 讓所有 TextBox 都添加一個綁定到 Validation.HasError 的 DataTrigger,當 Validation.HasError 為 True 時 TextBox 獲得焦點。這種做法可以寫少很多程式碼,但對具體業務來說可能不是很好用。
6. 最後
這篇文章只介紹了簡單的解決方案,最後還是需要根據自己的業務需求進行修改或封裝。View 和 ViewModel 交互可以是一個很龐大的話題,下次有機會再深入探討。
7. 參考
FocusManager.FocusedElement 附加屬性