假设有一个具有两个属性的 ViewModel,以及处理加载表单和更改文本的命令:
public class MyViewModel : ViewModelBase
{
public string TestString { get; set; } = "";
public string TestString2 { get; set; } = "";
private RelayCommand<RoutedEventArgs> _loadedCommand;
public RelayCommand<RoutedEventArgs> LoadedCommand =>
_loadedCommand ??= new RelayCommand<RoutedEventArgs>(Loaded);
private RelayCommand _textChangedCommand;
public RelayCommand TextChangedCommand =>
_textChangedCommand ??= new RelayCommand(TextChanged);
private void Loaded(RoutedEventArgs e)
{
TestString = "Loaded";
}
private void TextChanged()
{
TestString2 = "Modified";
}
}
XAML 形式:
<UserControl x:Class="WpfApp.Views.MyView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:WpfApp.Views"
xmlns:viewmodel="clr-namespace:WpfApp.ViewModels"
xmlns:i="http://schemas.microsoft.com/xaml/behaviors"
d:DataContext="{d:DesignInstance Type=viewmodel:MyViewModel}"
mc:Ignorable="d"
d:DesignHeight="800" d:DesignWidth="1200">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Loaded">
<i:InvokeCommandAction Command="{Binding LoadedCommand}" PassEventArgsToCommand="True"/>
</i:EventTrigger>
</i:Interaction.Triggers>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<TextBox Text="{Binding TestString}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="TextChanged">
<i:InvokeCommandAction Command="{Binding TextChangedCommand}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</TextBox>
<TextBlock Text="{Binding TestString2}" Grid.Column="1"/>
</Grid>
</UserControl>
TextBlock 应将其文本更改为“已修改”,但这不会发生,因为建立绑定需要太长时间,因此 TextChanged 事件在绑定完成之前发生。
如果添加延迟,则会出现“已修改”字样:
private async void Loaded(RoutedEventArgs e)
{
await Task.Delay(1000);
TestString = "Loaded";
}
有没有一个好的方法来解决这个问题?