manu
manu

Reputation: 1817

How to execute TextBox.scrolltoend in text_changed event using caliburn.micro using view model

I am using caliburn micro in my Wpf application. I would like to scroll down a text box when it's content is more. I don't want to use view's code behind to achieve this functionality. I have google it and found the following link.

Use view's code behind directly. Though it may be a workaround, I am not happy with this approach because I consider this is the starting point of bad practice.

I found one more reference to achieve similar functionality using Rx (reactive extensions)

Reactive Extensions for .NET (Rx) in WPF - MVVM

I don't know how to use it in the context of Caliburn Micro.

Similar question was asked by another stackoverflow member here however no satisfactory response.

I have to do two things.

  1. Subscribe Text Changed event
  2. Get the Textbox object from sender parameter (or somehow the textbox object) and execute ScrollToEnd() method of it

I guess it is possible either by IHandle of Caliburn micro or Rx(Reactive extensions). Could some one please help me how to achieve this functionality?

Upvotes: 0

Views: 1195

Answers (2)

stromms
stromms

Reputation: 161

Like m-y said in his comment, this is essentially a View operation and not a ViewModel's. Code behind on views is not immediately bad practice. Code behind on view is only bad when the operations needs dependencies past the View.

If you don't like code behind on the view, you can do it by using behaviors:

  public class TextBoxScrollToEndOnTextChanged:Behavior<TextBox>
  {
    protected override void OnAttached()
    {
      AssociatedObject.TextChanged += AssociatedObject_TextChanged;
    }

    protected override void OnDetaching()
    {
      AssociatedObject.TextChanged -= AssociatedObject_TextChanged;
    }

    void AssociatedObject_TextChanged(object sender, TextChangedEventArgs e)
    {
      AssociatedObject.ScrollToEnd();
    }
  }

xaml:

<TextBox>
    <i:Interaction.Behaviors>
        <behaviors:TextBoxScrollToEndOnTextChanged />
    </i:Interaction.Behaviors>
</TextBox>

Now if you have View - ViewModel interaction, I think this is the best way to do it.

Upvotes: 0

Derek Beattie
Derek Beattie

Reputation: 9478

Have you looked at using an IResult? They provide a way to accomplish this without coupling the view and viewmodel together.

A blurb from the docs:

Because coroutines occur inside of an Action, we provide you with an ActionExecutionContext useful in building UI-related IResult implementations. This allows the ViewModel a way to declaratively state it intentions in controlling the view without having any reference to a View or the need for interaction-based unit testing.

A example of playing a sound in SL with MediaElement and CM. Playing a sound in Silverlight with MediaElement and Caliburn Micro

Upvotes: 1

Related Questions