【发布时间】:2015-03-29 19:26:26
【问题描述】:
您好,我正在尝试绑定到不是DependencyProperty 的TextBox.CaretIndex 属性,所以我创建了一个Behavior,但它没有按预期工作。
期望(专注时)
- 默认 = 0
- 如果我更改我的 view 中的值,它应该更改我的 viewmodel 中的值
- 如果我更改 viewmodel 中的值,它应该更改我的 view 中的值
当前行为
- viewmodel 值在窗口打开时被调用
代码隐藏
public class TextBoxBehavior : DependencyObject
{
public static readonly DependencyProperty CursorPositionProperty =
DependencyProperty.Register(
"CursorPosition",
typeof(int),
typeof(TextBoxBehavior),
new FrameworkPropertyMetadata(
default(int),
new PropertyChangedCallback(CursorPositionChanged)));
public static void SetCursorPosition(DependencyObject dependencyObject, int i)
{
// breakpoint get never called
dependencyObject.SetValue(CursorPositionProperty, i);
}
public static int GetCursorPosition(DependencyObject dependencyObject)
{
// breakpoint get never called
return (int)dependencyObject.GetValue(CursorPositionProperty);
}
private static void CursorPositionChanged(
DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
{
// breakpoint get never called
//var textBox = dependencyObject as TextBox;
//if (textBox == null) return;
}
}
XAML
<TextBox Text="{Binding TextTemplate,UpdateSourceTrigger=PropertyChanged}"
local:TextBoxBehavior.CursorPosition="{Binding CursorPosition}"/>
更多信息
我认为这里确实有问题,因为我需要从以前从未需要的DependencyObject 派生它,因为CursorPositionProperty 已经是DependencyProperty,所以这应该足够了。我还认为我需要在我的Behavior 中使用一些事件来正确设置我的CursorPositionProperty,但我不知道是哪个。
【问题讨论】:
标签: c# wpf mvvm binding textbox