使自动专注于重命名上传文件C#WPF

时间:2018-10-09 11:41:06

标签: c# wpf focus

我有个主意,但我无法实现。我的wpf中有一些TextBox

<Button Content="Add" Command="{Binding AddAdditionalFileCommand}"  Name="MB" />
<TextBox  Text="{Binding SomeModel.File.FileName}" />

在我的虚拟机中

FileName = Path.GetFileName(file)

此文本框显示带有扩展名的已加载文件的名称。而且我可以更改文件名。好。我的想法是,当我单击按钮以上传文件时,并且在上传文件后,当文本框中出现文件名时,我想自动将焦点集中到文本框中的所有文件名,而无需扩展名。我可以这样做吗?

例如 上载名为test.mpkg的文件,并专注于不带mpkg的测试。想在Windows中重命名文件时。它专注于不带扩展名的文件名。

编辑 我在ViewModel中的命令

    private DelegateCommand addAdditionalFileCommand;
    public  DelegateCommand AddAdditionalFileCommand
    {
        get
        {
            if (addAdditionalFileCommand == null)
                addAdditionalFileCommand = new DelegateCommand(x =>
                {
                    var file = IOService.OpenFileDialog("", new string[] { "File|*.*" });
                    if (System.IO.File.Exists(file))
                    {
                        Model.Package = new ApplicationVersionPackage() {
                            FilePack = File.ReadAllBytes(file),
                            FileName = Path.GetFileName(file)
                        };


                    }


                });
            return addAdditionalFileCommand;
        }
        set
        {
            if (addAdditionalFileCommand != value)
            {
                addAdditionalFileCommand = value;
                NotifyPropertyChanged("AddAdditionalFileCommand");
            }
        }
    }

如何从文本框名称将此Select或Focus传递给此命令

1 个答案:

答案 0 :(得分:0)

上传文件后,您可以使用Select()来使文本框成为焦点。

做这样的事情。

textBoxFileName.Focus();

//The -3 is to avoid the extension maybe you can do a method to get the extension 
//length, because can has differents lengths (.jpg, .jpeg)

textBoxFileName.Select(0, Path.GetFileName(file).length -3); 

我不知道您是否熟悉WPF项目中使用的 MVVM模式(模型-视图-视图模型),但是它将大大帮助您将此类内容绑定到您的文本框和其他组件。

MVVM explained

MVVM example and tutorial