I need to bind the height of TextBox
es to my data model. The model should be updated each time a TextBox
gets resized. The TextBox
is resized because it wraps the content until MaxHeight
is reached, when it's reached it shows the scrollbar. I've made a little example to demonstrate my problem.
<Window x:Class="BindingTester.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:BindingTester"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Canvas>
<TextBox
Canvas.Left="234"
Canvas.Top="71"
Text="TextBox"
TextWrapping="Wrap"
ScrollViewer.VerticalScrollBarVisibility="Auto"
MaxHeight="200"
AcceptsReturn="True"
Height="{Binding TextBoxHeight, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged/>
</Canvas>
public partial class MainWindow : Window, INotifyPropertyChanged
{
private double textBoxHeight;
public MainWindow()
{
InitializeComponent();
DataContext = this;
//TextBoxHeight = 100.0;
}
public double TextBoxHeight
{
get { return textBoxHeight; }
set
{
if (value != textBoxHeight)
{
textBoxHeight = value;
RaisePropertyChanged("TextBoxHeight");
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
When I use this, the binding from source to target works fine. When I set the TextBoxHeight
property in the constructor of the MainWindow
the TextBox
resizes perfectly to 100, but the size seems to be fixed then. When I don't set it (because with a height of 100 it's much to large for the content "TextBox") first behaves like expected: the TextBox
's size fits the content. The TextBoxHeight
in the model gets updated to NaN
.
I know this happens because the Height
property returns NaN
when it is not set, instead I have to ask for ActualHeight
. But anyway, I recognized that if I enter some text (for example newlines) to resize the TextBox
's Height
, the TextBoxHeight
property still is not updated and the setter is not called again…I also have tried to use an IValueConverter
to update it using ActualHeight
without success.
I know in this example, even if I resize the TextBox
by entering newlines, TextBoxHeight
each time would be updated with NaN
, but the setter is just called the first time when the TextBox
is initialized. It confuses me that the Binding doesn't seem to work…I know a solution for the problem itself: subscribe the SizeChanged
event, get the DataContext
of sender object and set the model manually. But I think there should be a solution without subscribing and accessing the model in code-behind, only binding the properties. Can anybody help?