如何获取文本框的编辑前和编辑后?

How to get Before Edit and After Edit of a Textbox?

我正在使用 PRISM MVVM 显示包含图像、文件名和图像大小的文件列表视图。

用户应该能够通过键入新名称来更改文件的名称。 离开文本框时,我的 ViewModel 中的文件名应该重命名。为此,我当然需要了解前后的文本。

我不想使用Code behind,但我想我需要使用GotFocus 来存储LostFocus 之前和之上的值以获取新值。对吗?

这是我的XAML

  <Grid>   
    <ListView x:Name="MiscFilesListView" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" ItemsSource="{Binding MiscFiles}">
      <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
          <UniformGrid Columns="1" HorizontalAlignment="Stretch"/>
        </ItemsPanelTemplate>
      </ItemsControl.ItemsPanel>
      <ListView.ItemTemplate>
        <DataTemplate>
          <StackPanel Orientation="Vertical" VerticalAlignment="Top" HorizontalAlignment="Stretch">
            <Image Source="{Binding ImageData}" HorizontalAlignment="Center" VerticalAlignment="Top" Height="100" Width="100" />
            <TextBox Text="{Binding FileName}" HorizontalAlignment="Center" VerticalAlignment="Bottom" />
            <TextBlock Text="{Binding Size}" HorizontalAlignment="Center" VerticalAlignment="Bottom" />
          </StackPanel>
        </DataTemplate>
      </ListView.ItemTemplate>
    </ListView>
  </Grid>

列表视图绑定到:

public ObservableCollection<MiscFile> MiscFiles
{
   get => _miscFiles;
   set => SetProperty(ref _miscFiles, value);
}

视图模型

  public class MiscFile : INotifyPropertyChanged
  {
    public BitmapImage ImageData { get; set; }
    public string FileName { get; set; }
    public string FullFileName { get; set; }
    public string Size { get; set; }

    public void OnPropertyChanged(string propertyname)
    {
      PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyname));
    }

    public event PropertyChangedEventHandler PropertyChanged;
  }

知道如何在 Viewmodel 中实现这个吗? 我需要某种 EventTrigger 吗?

之前的值已经存储在您的 MiscFile 对象中。只需为您的 属性:

定义一个支持字段
private string _filename;
public string FileName
{
    get { return _filename; }
    set
    {
        string oldValue = _filename;
        string newValue = value;

        //update...
        _filename = value;
    }
}

这应该可以作为来源 属性 在 TextBox 失去焦点之前不应设置,因为您没有更改绑定的 UpdateSourceTrigger 属性从其默认值 LostFocus:

<TextBox Text="{Binding FileName, UpdateSourceTrigger=LostFocus}" ... />

您可以在视图模型中为文件名创建一个私有字段。 public FileName 属性 应该检查该值是否与私有字段中设置的值不同。还通过调用 OnPropertyChanged 通知 INotifyPropertyChanged。 这样做应该会更新文件名 属性.

如果您想保留旧文件名,可以调用静态路径的 Path.GetFileName(FullFileName) 方法 class。

private string _filename;
public BitmapImage ImageData
{
    get;set;
}

public string FileName
{
    get
    {
        return _filename;
    }
    set
    {
        if (_filename != value)
        {
            _filename = value;
            OnPropertyChanged(nameof(FileName));
        }
    }
}