【问题标题】:Change Property from within event trigger从事件触发器中更改属性
【发布时间】:2009-09-26 00:25:39
【问题描述】:

我想要的只是我所有的文本框默认设置它们的光标在文本的末尾,所以我想要伪代码:

if (TextChanged) textbox.SelectionStart = textbox.Text.Length;

因为我希望我的应用程序中的所有文本框都受到影响,所以我想为此使用一种样式。这个行不通(原因很明显),但你明白了:

<Style TargetType="{x:Type TextBox}">
  <Style.Triggers>
    <EventTrigger RoutedEvent="TextChanged">
      <EventTrigger.Actions>
        <Setter Property="SelectionStart" Value="{Binding Text.Length}"/>
      </EventTrigger.Actions>
    </EventTrigger>
  </Style.Triggers>
</Style>

编辑: 一件重要的事情是,仅当 Text 属性以编程方式分配时才应设置 SelectionStart 属性,而不是在用户编辑文本框时设置。

【问题讨论】:

    标签: c# .net wpf xaml triggers


    【解决方案1】:

    您确定要为您的应用中的所有文本框使用此行为吗?这将使用户几乎不可能(或至少非常痛苦)在 TextBox 中间编辑文本...

    无论如何,有一种方法可以做你想做的事……假设你的风格是在 ResourceDictionary 文件中定义的。首先,您需要为资源字典(例如 Dictionary1.xaml.cs)创建一个代码隐藏文件。在此文件中写入以下代码:

    using System.Windows.Controls;
    using System.Windows;
    
    namespace WpfApplication1
    {
        partial class Dictionary1
        {
            void TextBox_TextChanged(object sender, RoutedEventArgs e)
            {
                TextBox textBox = sender as TextBox;
                if (textBox != null)
                    textBox.SelectionStart = textBox.Text.Length;
            }
        }
    }
    

    在 XAML 中,将 x:Class 属性添加到 ResourceDictionary 元素:

    <ResourceDictionary x:Class="WpfApplication1.Dictionary1"
                        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    

    如下定义你的风格:

    <Style TargetType="{x:Type TextBox}">
        <EventSetter Event="TextChanged" Handler="TextBox_TextChanged" />
    </Style>
    

    TextBox_TextChanged 方法现在将处理所有文本框的TextChanged 事件。

    应该可以使用 x:Code 属性在 XAML 中编写内联代码,但我无法让它工作......

    【讨论】:

    • 哦该死的..我没想到这一点。如果文本以编程方式更改,我真的需要仅设置 SelectionStart,例如如果 Text 属性已分配给但不是由于用户编辑。
    • 我不知道你可以做这种事情 - 太棒了。
    【解决方案2】:

    创建一个attached behaviour。附加行为是一种连接任意事件处理的方式,它可以通过样式应用。

    【讨论】:

      猜你喜欢
      • 2011-06-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多