2017-05-29 63 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大聲笑,它把我扔了一圈實際上。我認爲它應該和你一樣好。 –