2009-09-26 100 views
2

我要的很簡單,就是我所有的文本框爲默認設置的光標停留在文本的末尾,所以我想在僞代碼:更改屬性

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> 

編輯: 一個重要的事情是,SelectionStart屬性應該只有在Text屬性通過編程分配,不設定時用戶編輯文本框。

回答

3

您確定要爲您的應用中的所有文本框應用此行爲嗎?它會使用戶在文本框中間編輯文本幾乎不可能(或者至少非常痛苦)...

無論如何,有一種方法可以做你想做的事......假設你的風格是在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加:類屬性的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在XAML代碼內聯:代碼屬性,但我不能讓它工作...

+0

哦該死的..我沒有想到這一點。如果文本以編程方式改變,我確實只需要設置SelectionStart,例如如果將Text屬性分配給但不是由於用戶編輯。 – codymanix 2009-09-26 15:19:03

+0

我不知道你可以做這種事 - 真棒。 – 2011-07-14 14:02:25