Reputation: 2666
For some purpose I wanted to raise an event whenever the LineCount
of a multiline textbox changes
I thought I could achieve this if I bind a dependency property to TextBox.LineCount
Below is the code sample
XAML
<local:MyTextBox Margin="5,65,5,5" x:Name="txtBox"
AcceptsReturn="True" AcceptsTab="False"
MyProperty="{Binding LineCount, RelativeSource={RelativeSource Self}}" />
Code-Behind
public class MyTextBox : TextBox
{
public MyTextBox()
{
DataContext = this;
}
public int MyProperty
{
get
{
return (int)this.GetValue(LineCountProperty);
}
set
{
this.SetValue(LineCountProperty, value);
}
}
public static readonly DependencyProperty LineCountProperty =
DependencyProperty.Register(
"MyProperty",
typeof(int),
typeof(TextBox),
new FrameworkPropertyMetadata(
new PropertyChangedCallback(
(dp, args) => { MessageBox.Show(args.NewValue.ToString()); })
));
}
The messagebox is shown only when the form is loaded and not after the line count changes.
However if I change the Binding for the MyProperty
from TextBox's LineCount
to Text
The PropertyChangedEvent is fired everytime the text changes.
I am sure I can fire some custom LineCount changed event from TextChanged eventhandler, but I want to do this via DepedencyProperties
for I believe it'll be more efficient.
Upvotes: 2
Views: 845
Reputation: 70142
The problem is that LineCount
is not a dependency property, see the MSDN documentation. For this reason it does not support binding and will not provide change notification.
Considering that you are making a custom control, do you really need to use binding? Why not just handle the TextChanged
event internally and detect when the line count changes manually.
Upvotes: 2