【问题标题】:Order of events in xamlxaml 中的事件顺序
【发布时间】:2013-09-16 21:24:41
【问题描述】:

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>

【问题讨论】:

  • 贴出相关代码和XAML。
  • WPF、windows phone、winRT哪个平台?
  • 为什么需要这样的行为?也许有更好的方法来做你想做的事情。
  • 打算在您列出的任何平台上使用

标签: .net xaml


【解决方案1】:

如果您需要在文本更改而不是失去焦点时更新文本,在 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}"(并删除正常的文本绑定)

【讨论】:

    【解决方案2】:

    一种可能的方式:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-12
      • 2014-12-08
      • 1970-01-01
      相关资源
      最近更新 更多