WPF命令键绑定的问题

时间:2017-05-29 17:59:08

标签: c# wpf xaml

我正在处理的项目需要一个快捷键来访问保存对话框,以将富文本框元素的内容转储到文件中。

我的键绑定和命令绑定正在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,也不会显示保存对话框。 如果有帮助,程序将全屏运行。

此外,有没有办法在WPF应用程序内部运行Winforms保存对话框作为单独的窗口

1 个答案:

答案 0 :(得分:0)

这对我来说是第一次尝试(至少直到SaveFileDialog抛出有关过滤字符串的异常)。我将KeyBinding放在Window.InputBindings中,将CommandBinding放在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; }
}

由于尾​​随管道字符,我得到了有关过滤字符串的异常。它似乎认为它是一个分隔符,而不是终结符:

  

提供的过滤字符串无效。过滤器字符串应包含过滤器的描述,后跟垂直条和过滤器模式。还必须通过垂直条分隔多个过滤器描述和模式对。必须使用分号分隔过滤器模式中的多个扩展名。示例:&#34;图像文件(* .bmp, .jpg)| .bmp; .jpg |所有文件()| *&#34;

轻松修复:

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名称的坚持是相对无害的,但它对可读性几乎没有作用。