Ich bin neu in MVVM und ich möchte eine rtf-Datei in einer RichTextBox mit MVVM laden, aber der Text scheint nicht in meiner Richtextbox anzuzeigen. Es sieht so aus, als wäre RichTextBox ziemlich komplex, wenn man versucht, die Befehle in ViewModel zu platzieren. Ich bin mir nicht sicher, wo ich falsch liege.Load rtf in bindbare RichTexBox mvvm wpf
Ansichtsmodell
FlowDocument _script;
public FlowDocument Script
{
get { return _script; }
set { _script = value; RaisePropertyChanged("Script"); }
}
.
.
.
private void LoadScript()
{
openFile.InitialDirectory = "C:\\";
if (openFile.ShowDialog() == true)
{
string originalfilename = System.IO.Path.GetFullPath(openFile.FileName);
if (openFile.CheckFileExists)
{
Script = new FlowDocument();
TextRange range = new TextRange(Script.ContentStart, Script.ContentEnd);
FileStream fStream = new FileStream(originalfilename, System.IO.FileMode.OpenOrCreate);
range.Load(fStream, DataFormats.Rtf);
fStream.Close();
}
}
}
die Ansicht
DataContext="{Binding ScriptBreakdownViewModel, Source={StaticResource Locator}}">
<Grid>
<RichTextBox
Local:RichTextBoxHelper.DocumentRtf="{Binding Script}"
x:Name="rtfMain"
HorizontalAlignment="Left"
Width="673"
VerticalScrollBarVisibility="Visible"
Margin="0,59,0,10.4"
/>
die RichTextBoxHelper
public class RichTextBoxHelper : DependencyObject
{
public static string GetDocumentRtf(DependencyObject obj)
{
return (string)obj.GetValue(DocumentRtfProperty);
}
public static void SetDocumentRtf(DependencyObject obj, string value)
{
obj.SetValue(DocumentRtfProperty, value);
}
public static readonly DependencyProperty DocumentRtfProperty =
DependencyProperty.RegisterAttached(
"DocumentRtf",
typeof(string),
typeof(RichTextBoxHelper),
new FrameworkPropertyMetadata
{
BindsTwoWayByDefault = true,
PropertyChangedCallback = (obj, e) =>
{
var richTextBox = (RichTextBox)obj;
// Parse the XAML to a document (or use XamlReader.Parse())
var Rtf = GetDocumentRtf(richTextBox);
var doc = new FlowDocument();
var range = new TextRange(doc.ContentStart, doc.ContentEnd);
range.Load(new MemoryStream(Encoding.UTF8.GetBytes(Rtf)),
DataFormats.Rtf);
// Set the document
richTextBox.Document = doc;
// When the document changes update the source
range.Changed += (obj2, e2) =>
{
if (richTextBox.Document == doc)
{
MemoryStream buffer = new MemoryStream();
range.Save(buffer, DataFormats.Rtf);
SetDocumentRtf(richTextBox,
Encoding.UTF8.GetString(buffer.ToArray()));
}
};
}
});
}
und das Modell
FlowDocument _script;
public FlowDocument Script // the Name property
{
get { return _script; }
set { _script = value; NotifyPropertyChanged("Script"); }
}
hilft Ihnen das in irgendeiner Weise? http://www.codeproject.com/Articles/137209/Binding-and-styling-text-to-a-RichTextBox-in-WPF – niksofteng
Wird Ihre 'LoadScript' Methode im ViewModel definitiv aufgerufen? –