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="https://www.cnblogs.com/dino623/p/5" />
<Setter Property="FontSize" Value="https://www.cnblogs.com/dino623/p/15" />
<Setter Property="Validation.ErrorTemplate" Value="https://www.cnblogs.com/dino623/p/{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="https://www.cnblogs.com/dino623/p/True">
<Setter Property="FocusManager.FocusedElement" Value="https://www.cnblogs.com/dino623/p/{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="https://www.cnblogs.com/dino623/p/True">
<Setter Property="FocusManager.FocusedElement" Value="https://www.cnblogs.com/dino623/p/{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 附加屬性
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/239363.html
標籤:WPF
