2017-05-29 62 views
0

我正在处理的项目需要使用快捷键访问保存对话框,以将富文本框元素的内容转储到文件中。WPF命令键绑定的问题

我的键绑定和命令绑定正在XAML中完成,但后面的代码是我认为搞乱了。

我的键和命令绑定是这样设置的。

<KeyBinding Command="local:customCommands.saveFile" Key="S" Modifiers="Ctrl"/> 
... 
<CommandBinding Command="local:customCommands.saveFile" Executed="launchSaveDialog"/> 

而这背后的WPF窗口

private void launchSaveDialog(object sender, ExecutedRoutedEventArgs e) 
    { 
     SaveFileDialog dlg = new SaveFileDialog(); 
     dlg.Filter = "Rich Text format(*.rtf)|*.rtf|"; 
     dlg.DefaultExt = ".rtf"; 
     dlg.OverwritePrompt = true; 
     if (dlg.ShowDialog() == true) 
     { 
      FileStream fileStream = new FileStream(dlg.FileName, FileMode.Create); 
      TextRange range = new TextRange(RTB.Document.ContentStart, RTB.Document.ContentEnd); 
      range.Save(fileStream, DataFormats.Rtf); 
     } 
    } 

代码保存对话框即使Ctrl + S键被按下不显示。 如果有帮助,程序全屏运行。

此外,有没有运行一个WinForms保存WPF应用程序的对话框内作为一个单独的窗口

+0

在XAML中定义的KeyBinding和CommandBinding在哪里?你可以通过在'launchSaveDialog'中放置一个断点来找出它是否调用'launchSaveDialog'。 –

+0

您绝对不会调用'launchSaveDialog',否则您会看到有关无效过滤器字符串的异常。您需要删除尾部管道('|')字符。 –

回答

0

这个工作的第一次尝试,我(至少直到SaveFileDialog扔关于过滤字符串异常的一种方式)。我把KeyBinding置于Window.InputBindingsCommandBinding置于Window.CommandBindings

<Window 
    x:Class="Test3.MainWindow" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:local="clr-namespace:Test3" 
    xmlns:commands="clr-namespace:Commands" 
    Title="MainWindow" 
    Height="350" 
    Width="525"> 
    <Window.InputBindings> 
     <KeyBinding Command="local:customCommands.saveFile" Key="S" Modifiers="Ctrl"/> 
    </Window.InputBindings> 
    <Window.CommandBindings> 
     <CommandBinding Command="local:customCommands.saveFile" Executed="launchSaveDialog"/> 
    </Window.CommandBindings> 
    <Grid> 
     <RichTextBox x:Name="RTB" /> 
    </Grid> 
</Window> 

我定义customCommands如下:

public static class customCommands 
{ 
    static customCommands() 
    { 
     saveFile = new RoutedCommand("saveFile", typeof(MainWindow)); 
    } 
    public static RoutedCommand saveFile { get; private set; } 
} 

我关于过滤字符串异常,由于后行管的字符。它似乎认为这是一个分隔符,而不是终结符:

提供的过滤字符串无效。过滤器字符串应该包含过滤器的描述,接着是一个垂直条和过滤器模式。还必须用垂直条分隔多个过滤器描述和模式对。必须用分号分隔过滤器模式中的多个扩展名。例如: “()。图片文件(* .BMP,.JPG)| | .BMP .JPG所有文件| *”

简单的解决办法:

private void launchSaveDialog(object sender, ExecutedRoutedEventArgs e) 
{ 
    SaveFileDialog dlg = new SaveFileDialog(); 
    dlg.Filter = "Rich Text format (*.rtf)|*.rtf"; 
    dlg.DefaultExt = ".rtf"; 
    dlg.OverwritePrompt = true; 
    if (dlg.ShowDialog() == true) 
    { 
     FileStream fileStream = new FileStream(dlg.FileName, FileMode.Create); 
     TextRange range = new TextRange(RTB.Document.ContentStart, RTB.Document.ContentEnd); 
     range.Save(fileStream, DataFormats.Rtf); 
    } 
} 

你可能在某处吃了键盘输入,但是你没有显示那个代码,所以我只是把它扔到那里。

对javaCase名称的坚持是相对无害的,但对可读性没什么作用。

+0

这工作。我不能相信我错过了那条管道-_- –

+0

@MichaelLaws大声笑,它把我扔了一圈实际上。我认为它应该和你一样好。 –