MVVM-附加属性selectionstart,文本框中的selectionlength

时间:2018-08-06 11:57:14

标签: c# wpf mvvm attached-properties

我试图通过附加属性在TextBox中绑定selectionstart和selectionlength。早些时候,我成功地绑定了此控件的设置焦点,但是我不知道为什么选择不起作用(选择方法中的断点永远不会触发)。我发现了与此问题相关的一些主题(例如:How to bind SelectionStart Property of Text Box?),但是在答案中,我仅看到在ctor中更改了选择事件的创建自定义控件。是否可以在不创建自定义控件的情况下实现呢?矿井代码:

public class TextBoxExtension
{
    public static readonly DependencyProperty IsFocusedProperty = DependencyProperty.RegisterAttached(
    "IsFocused", typeof(bool), typeof(TextBoxExtension), new UIPropertyMetadata(false, OnIsFocusedPropertyChanged));

    public static readonly DependencyProperty SelectionStartProperty = DependencyProperty.RegisterAttached(
    "SelectionStart", typeof(int), typeof(TextBoxExtension), new PropertyMetadata(OnSelectionStartPropertyChanged));

    public static readonly DependencyProperty SelectionLengthProperty = DependencyProperty.RegisterAttached(
    "SelectionLength", typeof(int), typeof(TextBoxExtension), new PropertyMetadata(OnSelectionLengthPropertyChanged));


    public static bool GetIsFocused(DependencyObject obj)
    {
        return (bool)obj.GetValue(IsFocusedProperty);
    }

    public static void SetIsFocused(DependencyObject obj, bool value)
    {
        obj.SetValue(IsFocusedProperty, value);
    }

    private static void OnIsFocusedPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var uie = (UIElement)d;
        if ((bool)e.NewValue)
        {
            Keyboard.Focus(uie);
            uie.Focus();
        }
    }

    public static int GetSelectionStart(DependencyObject obj)
    {
        return (int)obj.GetValue(SelectionStartProperty);
    }

    public static void SetSelectionStart(DependencyObject obj, int value)
    {
        obj.SetValue(SelectionStartProperty, value);
    }

    private static void OnSelectionStartPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var uie = (TextBox)d;
        uie.SelectionStart = (int)e.NewValue;
    }

    public static int GetSelectionLength(DependencyObject obj)
    {
        return (int)obj.GetValue(SelectionLengthProperty);
    }

    public static void SetSelectionLength(DependencyObject obj, int value)
    {
        obj.SetValue(SelectionLengthProperty, value);
    }

    private static void OnSelectionLengthPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var uie = (TextBox)d;
        uie.SelectionLength = (int)e.NewValue;
    }
}

Xaml:

TextBox x:Name="textBoxSetQuantity" att:TextBoxExtension.SelectionStart="{Binding SelectionStart, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" att:TextBoxExtension.SelectionLength="{Binding SelectionLength, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" att:TextBoxExtension.IsFocused="{Binding TextBoxFocus}"

0 个答案:

没有答案