如何绑定到 CaretIndex 又名文本框的光标位置

2023-11-23

嗨,我正在尝试绑定到TextBox.CaretIndex属性不是DependencyProperty,所以我创建了一个Behavior,但它没有按预期工作。

期望(集中注意力时)

  • 默认 = 0
  • 如果我改变我的值view它应该改变我的值视图模型
  • 如果我改变我的值视图模型它应该改变我的值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正确,但我不知道哪个。


在与我的行为作斗争之后,我可以向您展示99%工作解决方案

Behavior

using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;

namespace WpfMVVMTextBoxCursorPosition
{
    public class TextBoxCursorPositionBehavior : DependencyObject
    {
        public static void SetCursorPosition(DependencyObject dependencyObject, int i)
        {
            dependencyObject.SetValue(CursorPositionProperty, i);
        }

        public static int GetCursorPosition(DependencyObject dependencyObject)
        {
            return (int)dependencyObject.GetValue(CursorPositionProperty);
        }

        public static readonly DependencyProperty CursorPositionProperty =
                                           DependencyProperty.Register("CursorPosition"
                                                                       , typeof(int)
                                                                       , typeof(TextBoxCursorPositionBehavior)
                                                                       , new FrameworkPropertyMetadata(default(int))
                                                                       {
                                                                           BindsTwoWayByDefault = true
                                                                           ,DefaultUpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
                                                                       }
                                                                       );

        public static readonly DependencyProperty TrackCaretIndexProperty =
                                                    DependencyProperty.RegisterAttached(
                                                        "TrackCaretIndex",
                                                        typeof(bool),
                                                        typeof(TextBoxCursorPositionBehavior),
                                                        new UIPropertyMetadata(false
                                                                                , OnTrackCaretIndex));

        public static void SetTrackCaretIndex(DependencyObject dependencyObject, bool i)
        {
            dependencyObject.SetValue(TrackCaretIndexProperty, i);
        }

        public static bool GetTrackCaretIndex(DependencyObject dependencyObject)
        {
            return (bool)dependencyObject.GetValue(TrackCaretIndexProperty);
        }

        private static void OnTrackCaretIndex(DependencyObject dependency, DependencyPropertyChangedEventArgs e)
        {
            var textbox = dependency as TextBox;

            if (textbox == null)
                return;
            bool oldValue = (bool)e.OldValue;
            bool newValue = (bool)e.NewValue;

            if (!oldValue && newValue) // If changed from false to true
            {
                textbox.SelectionChanged += OnSelectionChanged;
            }
            else if (oldValue && !newValue) // If changed from true to false
            {
                textbox.SelectionChanged -= OnSelectionChanged;
            }
        }

        private static void OnSelectionChanged(object sender, RoutedEventArgs e)
        {
            var textbox = sender as TextBox;

            if (textbox != null)
                SetCursorPosition(textbox, textbox.CaretIndex); // dies line does nothing
        }
    }
}

XAML

    <TextBox Height="50" VerticalAlignment="Top"
             Name="TestTextBox"
             Text="{Binding MyText}"
             vm:TextBoxCursorPositionBehavior.TrackCaretIndex="True"
             vm:TextBoxCursorPositionBehavior.CursorPosition="{Binding CursorPosition,Mode=TwoWay}"/>

    <TextBlock Height="50" Text="{Binding CursorPosition}"/>

只是有件事我不知道为什么它不起作用=>BindsTwoWayByDefault = true。据我所知,它对绑定没有影响,因此我需要在 XAML 中显式设置绑定模式

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何绑定到 CaretIndex 又名文本框的光标位置 的相关文章

随机推荐

  • PHP 确定多个(n)日期时间范围何时相互重叠

    我正在努力解决以下问题 这是一个日历程序 给定多个人的一组可用日期时间集 我需要找出每个人在 PHP 中可用的日期时间范围 可用性集 p1 start 2016 04 30 12 00 end 2016 05 01 03 00 p2 sta
  • 如何检测用户的区域设置以获得正确的 csv 分隔符?

    我有一个简单的数据转换工具 它可以生成的输出之一是 csv 文件 这在英国非常有效 但当我将其运送给德国客户时 我遇到了一些问题 具体来说 他们使用 表示浮点数中的小数点 反之亦然 这意味着当他们在 Excel 中打开数据文件时 结果至少可
  • 如何使用四开同时编织两种格式?

    是否可以通过在 YAML 标头中指定来一次从 Quarto R Markdown 文档创建多种输出格式 我的猜测没有成功 title Stacked Area chart with Annotations format html gfm 尝
  • jqGrid - rowObject 不一致?

    带有 jqgrid rowObject 的第一页结果返回预期数据 但随后返回后续结果页的不完整数据 为什么 结果第一页 rowObject 3 将等于 2 结果的后续页面 rowObject 3 将等于 未定义 并且返回结果的第一页现在也将
  • 可选参数和继承

    我了解可选参数 并且非常喜欢它们 但我想更多地了解如何将它们与继承的接口一起使用 附件A interface IMyInterface string Get string Get string str class MyClass IMyIn
  • Amazon API Gateway:通过 Postman 调用 API 时,响应正文未转换?

    通过 AWS API Gateway 控制台执行测试时 我发现 Lambda 函数的输出响应已正确转换 type message request id 请参阅下面的日志 Tue Sep 06 14 46 06 UTC 2016 Endpoi
  • 删除R中的冗余列[重复]

    这个问题在这里已经有答案了 我有类似的东西 date pgm in x logs out y 20130514 na 12 j1 12 20131204 z2 03 j1 03 20130516 a01 04 j0 04 20130628
  • 迭代 numpy 数组列的所有成对组合

    我有一个大小为 numpy 的数组 arr size 200 600 20 我想计算scipy stats kendalltau在最后两个维度的每个成对组合上 例如 kendalltau arr 0 0 arr 1 0 kendalltau
  • JSP EL ${stuff} 语法不起作用

    我有两个问题 第一个是我使用JSP 无法解决 第二个是我的行为很奇怪 当我将其放入 servlet 的 doGet 方法中时 req setAttribute test SARASA req getRequestDispatcher WEB
  • df1 中不在 df2 中的所有行

    我有一个 df df1 如下所示 df1 pd DataFrame YYZ SFO 1 YYZ YYD 1 YYZ EWR 1 YYZ DFW 1 YYZ LAX 1 YYZ YYC 1 columns city1 city2 val 我有
  • 你能解释一下Java中的“isXxx”方法名称吗?

    规范之一中是否引用了以 is 开头的方法 而方法名称的后缀是属性名称 类似于 Java bean 的 getter setter 方法 例如 public boolean isConditionTrue private boolean co
  • CRM 365 callManagerInfo 插件中出现错误

    将 CRM 2013 本地升级到 CRM365 后 开始出现插件问题 每次我尝试使用插件中的 IOrganizationService 进行任何操作时 我都会收到错误 此问题仅在多服务器安装时出现 在CRM 2013版本上没有出现这种情况
  • 如何启用“启用.NET Framework 源代码步进”?

    2013 年 2 月 22 日更新 Microsoft Connect 条目有 Alok Shriram 程序经理 基类库 NET Framework 的注释 该问题现在应该得到解决 连接条目标记为已解决 已修复 这个问题现在应该得到解决
  • Android 类 BaseAdapter 中的 getItem 和 getItemId 方法的用途是什么?

    我很好奇这些方法的目的getItem and getItemId在 Android SDK 的 Adapter 类中 从描述来看 似乎getItem应该返回底层数据 所以 如果我有一个名字数组 cat dog red 我创建了一个适配器a使
  • 将数组中的连续数字分组

    我需要将连续数字添加到新数组中 如果不是连续数字 则仅将该值添加到新数组中 old array 1 2 3 5 7 8 9 20 21 23 29 我想得到这个结果 new array 1 2 3 5 7 8 9 20 21 23 29 有
  • 如何在 swift 3.0 中连接多个可选字符串?

    我正在尝试在 swift 3 中连接多个字符串 var a String a var b String b var c String c var d String a b c 编译时我收到以下错误 error cannot convert
  • 如何在 tail -f 命令后继续运行脚本

    我有以下脚本 tail f nohup out echo 5 When I press Ctrl C on tail f the script stops running the 5 is not printed How can I run
  • JScript.NET 可以用于编写 .NET 应用程序脚本吗?

    自从多发性硬化症似乎已在最新的 DLR 中终止了托管 JavaScript对于服务器端 ASP NET Futures 和客户端 Silverlight 是否有人成功使用未过时的 API 来允许使用 JScript NET 编写其应用程序对
  • Javamail API - 如何将 setFrom 更改为您想要的任何内容?

    如何将 setFrom 方法更改为我想要的方法 我可以通过我的 gmail 帐户发送电子邮件并更改 setFrom 文本 但它显示了我的username对于电子邮件 我也尝试使用我的雅虎帐户 但收到身份验证错误 我想更改发件人地址 代码如下
  • 如何绑定到 CaretIndex 又名文本框的光标位置

    嗨 我正在尝试绑定到TextBox CaretIndex属性不是DependencyProperty 所以我创建了一个Behavior 但它没有按预期工作 期望 集中注意力时 默认 0 如果我改变我的值view它应该改变我的值视图模型 如果