tsragravorogh
tsragravorogh

Reputation: 3173

WPF MVVM changing TextBox size as you type

I have a TextBox and as its content grows I want it to grow and as its content shrinks I want it to shrink in terms of both its Height and Width. This can be easily achieved by hooking to the TextChanged event in TextBox, which means code-behind, something that we should avoid in MVVM. So the question is how do we do this in MVVM ? We have to use Commands obviously (classes implementing ICommand interface), at the same time we cannot hook Commands to events.

One option is to use System.Windows.Interactivity. I have used it before and it was pretty neat, but some folks might actually be against it given the fact its more of Silverlight library to use.

Any other options ?

A simpler XAML. Please note that I want the Window to change it's size, because the TextBox is taking the whole Window:

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid HorizontalAlignment="Stretch">
        <TextBox Width="Auto">            
        </TextBox>
    </Grid>
</Window>

Here is my XAML:

<Window x:Class="SleekNoteUI.Views.SleekNoteView"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    <Window.Template>
        <ControlTemplate>
            <Border...>
                <Grid>
                    <Grid Grid.Row="1" x:Name="noteGrid">
                        <TextBox Grid.Row="0"
                                 Text="{Binding SomeText...}"
                                 Background="{Binding...}">
            </TextBox>
        </Grid>
        </Grid>
    </Border>
    </ControlTemplate>
</Window.Template>
</Window>

Upvotes: 0

Views: 1977

Answers (3)

Zorro
Zorro

Reputation: 181

using System.Windows.Interactivity create a Behavior. This is the best way of encapsulating code that otherwise would endup in a code-behind

Upvotes: 0

Ramesh
Ramesh

Reputation: 386

By simply setting Width property to 'Auto' you can achieve this.

<TextBox Width="Auto" />

Thanks, Ramesh

Upvotes: 1

Fede
Fede

Reputation: 44068

Textbox Shrink / Grow as text changes:

<TextBox HorizontalAlignment="Left" Width="Auto" MinWidth="10"/>
  • XAML-only solution.
  • No code behind,
  • No System.Windows.Interactivity.
  • And not putting size-related things in the ViewModel, which they don't belong into.

And again:

  • MVVM is not about avoiding code behind. It's about separating UI from business/application logic and data.
  • System.Windows.Interactivity is as much WPF as it is Silverlight, so I don't know what "some folks" are talking about, but it's use is perfectly valid

Upvotes: 6

Related Questions