出于某种目的,我想在LineCount
多行文本框更改
时引发一个事件,我认为如果我将依赖属性绑定到以下是代码示例
,我可以实现 TextBox.LineCount
XAML
<local:MyTextBox Margin="5,65,5,5" x:Name="txtBox"
AcceptsReturn="True" AcceptsTab="False"
MyProperty="{Binding LineCount, RelativeSource={RelativeSource Self}}" />
代码隐藏
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()); })
));
}
消息框仅在加载表单时显示,而不是在行数更改后显示。
但是,如果我将TextBox 的
Binding 更改为PropertyChangedEvent
,则会在每次文本更改时触发。
我确信我可以从 TextChanged 事件处理程序中触发一些自定义的 LineCount 更改事件,但我想通过这样做,因为我相信它会更有效。MyProperty
LineCount
Text
DepedencyProperties