首页 > 解决方案 > 如何获得文本框的编辑前和编辑后?

问题描述

我正在使用 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>

Listview 必须:

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 吗?

标签: c#wpfmvvmprism

解决方案


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

如果要保留旧文件名,可以调用Path.GetFileName(FullFileName)静态 Path 类的方法。

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

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

推荐阅读