我可以在代码隐藏中轻松做到这一点,但不想破坏 MVVM
图案。
我有一个 RichTextBox
和我的 View 中的“保存”按钮。我想在单击“保存”按钮时将 RichTextBox 的内容保存到文件中。
我编写了一个委托(delegate)类,它期望一个方法返回 void 并具有单个对象参数。我这样做是因为我无法使用 System.Action 委托(delegate)。
class BtnCommandParameterised : ICommand
{
public delegate void ActionParameterised(object rtb);
private ActionParameterised _actionParameterised;
public object _object;
public BtnCommandParameterised(ActionParameterised BtnCommandParameterisedActionParameterised)
{
_actionParameterised = BtnCommandParameterisedActionParameterised;
}
public bool CanExecute(object parameter)
{
return true;
}
public void Execute(object parameter)
{
_actionParameterised.Invoke(_object);
}
public event EventHandler CanExecuteChanged;
}
然后在我的 ViewModel 我有一个
InitialiseBtnCommands()
从构造函数调用的方法。这将初始化命令: private void InitialiseBtnCommands()
{
ReturnTextAsStringCommand = new BtnCommandParameterised(ReturnTextAsStringCommandAction);
}
这会调用我的方法来保存文件。
private void ReturnTextAsStringCommandAction(object Document)
{
TextRange range;
FileStream fileStream;
range = new TextRange(((FlowDocument)Document).ContentStart,
((FlowDocument)Document).ContentEnd);
fileStream = new FileStream(FileName, FileMode.Create);
range.Save(fileStream, DataFormats.Text);
fileStream.Close();
Xceed.Wpf.Toolkit.MessageBox.Show("Text File Saved");
}
最后,在 View XAML 中,这是我的绑定(bind):
<Grid Name="MainGrid" DataContext="{StaticResource EditorViewModel}">
<xctk:RichTextBox SpellCheck.IsEnabled="True" HorizontalAlignment="Center" Margin="206,166,206,60" Name="richTextBoxArticleBody" AcceptsTab="True" BorderBrush="Silver" BorderThickness="1" VerticalAlignment="Center" Height="306" Width="600" FontFamily="Arial"/>
<Button Command="{Binding ReturnTextAsStringCommand}" CommandParameter="{Binding ElementName=richTextBoxArticleBody, Path=Document}" Content="Save Article Text" Height="23" HorizontalAlignment="Left" Margin="703,478,0,0" Name="button1" VerticalAlignment="Top" Width="103" />
</Grid>
正在调用命令并调用我的方法,但没有任何内容传递到
ReturnTextAsStringCommandAction
方法?我是 MVVM 的新手,发现我们应该说的东西,有点困惑。
最佳答案
您将 _object 传递给调用方法。
我认为您的意思是传递参数。
public void Execute(object parameter)
{
_actionParameterised.Invoke(parameter);
}
关于c# - 保存 RichTextBox 的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21939222/