Reputation: 3173
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
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
Reputation: 386
By simply setting Width property to 'Auto' you can achieve this.
<TextBox Width="Auto" />
Thanks, Ramesh
Upvotes: 1
Reputation: 44068
Textbox Shrink / Grow as text changes:
<TextBox HorizontalAlignment="Left" Width="Auto" MinWidth="10"/>
System.Windows.Interactivity
. And again:
Upvotes: 6