c# - 如何获得文本框的编辑前和编辑后?
问题描述
我正在使用 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 吗?
解决方案
您可以在视图模型中为文件名创建一个私有字段。公共 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));
}
}
}
推荐阅读
- django - 如何对合并的查询集进行排序 Django
- netsuite - 如何从子列表中读取项目数据
- python - 受让人 如果定义了环境变量,则对变量为真
- r - 无法将数据框中的日期列插入 SQL Server 中的日期列
- asp.net-mvc - 在 Asp.net 中使用身份验证重定向到花药网站
- c# - 未调用静态构造函数?
- firebase - BigQuery:将重复记录转换为列
- python - 如何在决策树回归中合并两年排名数据集
- smtp - 如何在 Cpanel 上启用建立 SMTP 连接?
- wordpress - 如何仅在 woocoomerce 管理部分向产品添加自定义元框