1

xaml 新手。我有一个 TextBox,其中文本值和更改的事件都绑定在 xaml 中。当键入一个值时,我需要在更改事件之前运行文本的值绑定机制。我该如何执行?

<TextBox x:Class="WPF.AppControls.TextBoxAppControl"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
    IsEnabled="{Binding Enabled}"
    Visibility="{Binding Visibility}"
    Text="{Binding Text}" 
    GotFocus="TextBox_GotFocus"
    LostFocus="TextBox_LostFocus"
    TextChanged="TextBox_TextChanged"
    KeyDown="TextBox_KeyDown">

</TextBox>
4

2 回答 2

0

一种可能的方式:

将自定义依赖属性 ( http://msdn.microsoft.com/en-us/library/ms753358.aspx ) 绑定到 TextBox.Text 并指定 PropertyChangedCallback ( http://msdn.microsoft.com/en-us/library/system .windows.propertychangedcallback.aspx)。

于 2013-09-16T21:41:45.600 回答
0

如果您需要在文本更改而不是失去焦点时更新文本,在 WPF 上,您可以将绑定替换为Text="{Binding Text,UpdateSourceTrigger=PropertyChanged}"
在其他平台上,您将需要创建一个附加属性,应该这样做:

public class MyAttachedProperties
{
    public static readonly DependencyProperty MyTextProperty =
        DependencyProperty.RegisterAttached("MyText", typeof (string), typeof (MyAttachedProperties), new PropertyMetadata(default(string),TextChanged));

    private static void TextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {

        TextBox tb = d as TextBox;

        tb.TextChanged -= tb_TextChanged;
        tb.TextChanged += tb_TextChanged;
        string newText = e.NewValue as String;
        if (tb.Text != newText)
        {
            tb.Text = newText;
        }
    }

    static void tb_TextChanged(object sender, TextChangedEventArgs e)
    {
        TextBox tb = sender as TextBox;
        SetMyText(tb, tb.Text);

    }

    public static void SetMyText(UIElement element, string value)
    {
        element.SetValue(MyTextProperty, value);
    }

    public static string GetMyText(UIElement element)
    {
        return (string) element.GetValue(MyTextProperty);
    }
}

您可以像这样使用:(local:MyAttachedProperties.MyText="{Binding Text}"并删除正常的文本绑定)

于 2013-09-16T21:35:21.160 回答