我在MVVM应用程序中使用avalon text editor
由于其Text属性不可绑定,因此我使用this answer来避免此问题
public sealed class AvalonEditBehaviour : Behavior<TextEditor>
{
public static readonly DependencyProperty ContentProperty =
DependencyProperty.Register("Content", typeof(string), typeof(AvalonEditBehaviour),
new FrameworkPropertyMetadata(default(string), FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, PropertyChangedCallback));
public string Content
{
get { return (string)GetValue(ContentProperty); }
set { SetValue(ContentProperty, value); }
}
protected override void OnAttached()
{
base.OnAttached();
if (AssociatedObject != null)
AssociatedObject.TextChanged += AssociatedObjectOnTextChanged;
}
protected override void OnDetaching()
{
base.OnDetaching();
if (AssociatedObject != null)
AssociatedObject.TextChanged -= AssociatedObjectOnTextChanged;
}
private void AssociatedObjectOnTextChanged(object sender, EventArgs eventArgs)
{
var textEditor = sender as TextEditor;
if (textEditor != null)
{
if (textEditor.Document != null)
Content = textEditor.Document.Text;
}
}
private static void PropertyChangedCallback(
DependencyObject dependencyObject,
DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
{
var behavior = dependencyObject as AvalonEditBehaviour;
if (behavior.AssociatedObject != null)
{
var editor = behavior.AssociatedObject as TextEditor;
if (editor.Document != null)
{
var caretOffset = editor.CaretOffset;
if (dependencyPropertyChangedEventArgs.NewValue != null)
{
editor.Document.Text = dependencyPropertyChangedEventArgs.NewValue.ToString();
editor.CaretOffset = caretOffset;
}
}
}
}
}
还有XAML
<AdornerDecorator Grid.Row="0" Margin="5">
<avalonedit:TextEditor
Name="textEditor"
Validation.ErrorTemplate="{StaticResource ValidationTemplate}"
FontFamily="Consolas"
FontSize="10pt">
<i:Interaction.Behaviors>
<behaviours:AvalonEditBehaviour Content="{Binding Package.ActionJson, Mode=TwoWay, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged}"/>
</i:Interaction.Behaviors>
</avalonedit:TextEditor>
</AdornerDecorator>
验证模板
<ControlTemplate x:Key="ValidationTemplate">
<StackPanel>
<Border BorderBrush="Red" BorderThickness="3">
<AdornedElementPlaceholder/>
</Border>
<TextBlock Foreground="Red" FontSize="14" Text="{Binding [0].ErrorContent}"></TextBlock>
</StackPanel>
</ControlTemplate>
<Style TargetType="{x:Type avalonedit:TextEditor}">
<Setter Property="VerticalAlignment" Value="Stretch"/>
<!--the 'standard' template for rendering error messages as a tooltip-->
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="true">
<Setter Property="ToolTip"
Value="{Binding RelativeSource={RelativeSource Self},
Path=(Validation.Errors)/ErrorContent}"/>
</Trigger>
</Style.Triggers>
</Style>
当我使用标准文本框时,它可以工作,但是尽管在更改绑定属性时验证代码会触发,但文本编辑器周围的红色框和下面的验证错误文本块都看不到。