首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >WPF,可绑定的richTextBox与MVVM (Caliburn.Micro)-Document已经属于另一个RichTextBox

WPF,可绑定的richTextBox与MVVM (Caliburn.Micro)-Document已经属于另一个RichTextBox
EN

Stack Overflow用户
提问于 2010-12-22 16:08:52
回答 1查看 2.9K关注 0票数 1

我有一个很有趣的问题。我在WPF应用程序中使用了这些技术: Caliburn.Micro和MEF。

我从视图模型打开新窗口(而不是屏幕)。效果很好。

Init-View-Model中,我有这样的方法,它打开新的WPF窗口,而不是在shell中屏幕。

代码语言:javascript
运行
复制
...

        public IEnumerable<IResult> Send()
        {
            yield return new ShowWindow("NewScreen")
                .InitializeWith(_service.DetailData(Account,_selectedFriend.Key));
        }
...

ShowWindow类如下所示:

代码语言:javascript
运行
复制
public class ShowWindow : IResult
{
    readonly Type _windowType;
    readonly string _name;

    [Import]
    public IShellViewModel Shell { get; set; }

    Action<object> _initializationAction = window => { };

    public ShowWindow InitializeWith<T>(T argument)
    {
        _initializationAction = window =>
        {
            var initializable = window as IInitializable<T>;
            if (initializable != null)
                initializable.Initialize(argument);
        };
        return this;
    }

    public ShowWindow(string name)
    {
        _name = name;
    }

    public ShowWindow(Type windowType)
    {
        _windowType = windowType;
    }

    public void Execute(ActionExecutionContext context)
    {
        var window = !string.IsNullOrEmpty(_name)
            ? IoC.Get<object>(_name)
            : IoC.GetInstance(_windowType, null);

        _initializationAction(window);

        IoC.Get<IWindowManager>().Show(window);

        Completed(this, new ResultCompletionEventArgs());
    }

    public event EventHandler<ResultCompletionEventArgs> Completed = delegate { };

    public static ShowWindow Of<T>()
    {
        return new ShowWindow(typeof(T));
    }
}

我使用事件聚合器将消息从init视图模型发送到新窗口。

在我添加了richtebox控件之前,一切都进行得很好。我需要可绑定的丰富的文本框。所以我

使用Jason (http://social.msdn.microsoft.com/forums/en-US/wpf/thread/f77c011a-0aba-449f-b6f4-920e58ebf997/)的可绑定版本

New-View-Model看起来是这样的:

代码语言:javascript
运行
复制
public class NewViewModel : Screen, IInitializable<DetailData>, IHandle<string>
{
    private IEventAggregator _eventAgg;

    private FlowDocument _conversation;

    //bind on document of richtextBox
    public FlowDocument Conversation
    {
        get { return _conversation; }
        set
        {
            _conversation = value;
            NotifyOfPropertyChange("Conversation");
        }
    }

    [ImportingConstructor]
    public NewViewModel(IEventAggregator eventAgg)
    {
        _eventAgg = eventAgg;
        _eventAgg.Subscribe(this);

        **//I think problem is here
        _conversation = new FlowDocument();**
    }

    public void Handle(string message)
    {
        Conversation.Blocks
            .Add(new Paragraph(new Run(message)));
    }
}

在New类中,我绑定了视图中RichTextBox上的属性会话。

视图:

代码语言:javascript
运行
复制
   <Controls:BindableRichTextBox    Document="{Binding Path=Conversation, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}"
                                    VerticalScrollBarVisibility="Auto" 
                                    HorizontalScrollBarVisibility="Auto"
                                    FontSize="13"
                                    Margin="4,4,4,4" 
                                    Grid.Row="0" />

问题是。

  1. ,我从Init-View-Model ->调用方法public IEnumerable Send(),它称为new Model ->的构造师,并打开了新的窗口。这是正确的,
  2. 比我第二次调用方法public IEnumerable Send()更正确,我得到了以下错误: System.Argument.Exception {“文档已经属于另一个IEnumerable

我在可绑定richTextBox类中得到了这个错误。

代码语言:javascript
运行
复制
...

        protected override void OnInitialized(EventArgs e)
        {
            // Hook up to get notified when DocumentProperty changes.
            DependencyPropertyDescriptor descriptor = DependencyPropertyDescriptor.FromProperty(DocumentProperty, typeof(BindableRichTextBox));
            descriptor.AddValueChanged(this, delegate
            {
                // If the underlying value of the dependency property changes,
                // update the underlying document, also.
**line 54:        base.Document = (FlowDocument)GetValue(DocumentProperty);**

            });

            // By default, we support updates to the source when focus is lost (or, if the LostFocus
            // trigger is specified explicity.  We don't support the PropertyChanged trigger right now.
            this.LostFocus += new RoutedEventHandler(BindableRichTextBox_LostFocus);

            base.OnInitialized(e);

        }

....

我认为问题是因为它只调用了一次New的构造函数。所以我调用了5次方法Send,但是它只调用了一次新建视图模型的构造函数。如何解决这个问题?

StackTrace:

代码语言:javascript
运行
复制
   at System.Windows.Controls.RichTextBox.set_Document(FlowDocument value)
   at Spirit.Controls.BindableRichTextBox.b__0(Object , EventArgs ) in C:\Users\Jan\Documents\Visual Studio 2010\Projects\C#\Pokec_Messenger\ver.beta\Pokec__Messenger\Spirit_v1.2\Controls\BindableRichTextBox.cs:line 54
   at MS.Internal.ComponentModel.PropertyChangeTracker.OnPropertyInvalidation(DependencyObject d, DependencyPropertyChangedEventArgs args)
   at System.Windows.DependentList.InvalidateDependents(DependencyObject source, DependencyPropertyChangedEventArgs sourceArgs)
   at System.Windows.DependencyObject.NotifyPropertyChange(DependencyPropertyChangedEventArgs args)
   at System.Windows.DependencyObject.UpdateEffectiveValue(EntryIndex entryIndex, DependencyProperty dp, PropertyMetadata metadata, EffectiveValueEntry oldEntry, EffectiveValueEntry& newEntry, Boolean coerceWithDeferredReference, Boolean coerceWithCurrentValue, OperationType operationType)
   at System.Windows.DependencyObject.InvalidateProperty(DependencyProperty dp)
   at System.Windows.Data.BindingExpressionBase.Invalidate(Boolean isASubPropertyChange)
   at System.Windows.Data.BindingExpression.TransferValue(Object newValue, Boolean isASubPropertyChange)
   at System.Windows.Data.BindingExpression.Activate(Object item)
   at System.Windows.Data.BindingExpression.AttachToContext(AttachAttempt attempt)
   at System.Windows.Data.BindingExpression.MS.Internal.Data.IDataBindEngineClient.AttachToContext(Boolean lastChance)
   at MS.Internal.Data.DataBindEngine.Task.Run(Boolean lastChance)
   at MS.Internal.Data.DataBindEngine.Run(Object arg)
   at MS.Internal.Data.DataBindEngine.OnLayoutUpdated(Object sender, EventArgs e)
   at System.Windows.ContextLayoutManager.fireLayoutUpdateEvent()
   at System.Windows.ContextLayoutManager.UpdateLayout()
   at System.Windows.ContextLayoutManager.UpdateLayoutCallback(Object arg)
   at System.Windows.Media.MediaContext.InvokeOnRenderCallback.DoWork()
   at System.Windows.Media.MediaContext.FireInvokeOnRenderCallbacks()
   at System.Windows.Media.MediaContext.RenderMessageHandlerCore(Object resizedCompositionTarget)
   at System.Windows.Media.MediaContext.RenderMessageHandler(Object resizedCompositionTarget)
   at System.Windows.Media.MediaContext.Resize(ICompositionTarget resizedCompositionTarget)
   at System.Windows.Interop.HwndTarget.OnResize()
   at System.Windows.Interop.HwndTarget.HandleMessage(WindowMessage msg, IntPtr wparam, IntPtr lparam)
   at System.Windows.Interop.HwndSource.HwndTargetFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
   at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
   at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
   at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
   at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)

问题出在哪里,我尝试了很多方法,但任何方法都行不通。谢谢你的建议和帮助。我很无助。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2010-12-26 16:43:42

我的解决方案:

我用PartCreationPolicy(CreationPolicy.NonShared),标记我的新视图模型,因为MEF的默认生存期是共享的(单例)。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4511097

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档