2011-02-11 139 views
8

guys 我想輸入多行文本到DataGridTextColumn中,我可以使用「enter」輸入一個多行字符。但我想使用像視覺工作室資源管理器一樣的「shift + enter」,這裏是我用「輸入」鍵的代碼。你可以這樣做WPF:DataGrid如何輸入多行文本

<DataGridTextColumn Header="Value" Binding="{Binding Value}" Width="*"> 
    <DataGridTextColumn.ElementStyle> 
     <Style TargetType="TextBlock"> 
     <Setter Property="TextWrapping" Value="Wrap" /> 
     </Style> 
    </DataGridTextColumn.ElementStyle> 
    <DataGridTextColumn.EditingElementStyle> 
     <Style TargetType="TextBox"> 
     <Setter Property="TextWrapping" Value="Wrap" /> 
     <Setter Property="AcceptsReturn" Value="true" /> 
     </Style> 
    </DataGridTextColumn.EditingElementStyle> 

回答

13

一種方式是通過處理上使用您的風格的EventSetter文本框的KeyDown事件。我接下你的例子,刪除了樣式中的AcceptsReturn設置器,並向EditingElementStyle添加了一個KeyDown處理器,該處理器向插入的位置添加一個換行符,並將CaretIndex移動到右側。

這裏的XAML:

<DataGridTextColumn Header="Value" Binding="{Binding Value}" Width="*"> 
    <DataGridTextColumn.ElementStyle> 
     <Style TargetType="TextBlock"> 
      <Setter Property="TextWrapping" Value="Wrap" /> 
     </Style> 
    </DataGridTextColumn.ElementStyle> 
    <DataGridTextColumn.EditingElementStyle> 
     <Style TargetType="TextBox"> 
      <Setter Property="TextWrapping" Value="Wrap" /> 
      <EventSetter Event="KeyDown" Handler="OnTextBoxKeyDown"/> 
     </Style> 
    </DataGridTextColumn.EditingElementStyle> 
</DataGridTextColumn> 

我寫的窗口類的例子,從一個新的應用程序項目模板,所以這裏的C#整個窗口的事件處理代碼。請注意,我將Handled設置爲true以阻止事件在任何地方冒泡,因爲我不希望在此情況下將Return鍵作爲對編輯行的提交進行處理。我認爲這實際上是這種方法的缺點之一。如果你的應用程序中的用戶輸入有複雜的相互作用,那麼停止事件的冒泡/隧道就可以很容易地變成邏輯炸彈。但是,如果你只是有一個這樣的特殊情況,它並不是那麼糟糕。因此,與所有內容一樣,謹慎使用,因爲使用此功能的用戶界面部分會增加。

public partial class MainWindow : Window 
{ 
    public MainWindow() 
    { 
     InitializeComponent(); 
     this.DataContext = new List<Thing> 
     { 
      new Thing { Value = "Some text" }, 
      new Thing { Value = "More text" + Environment.NewLine + " second line" }, 
      new Thing { Value = "Another value" } 
     }; 
    } 

    private void OnTextBoxKeyDown(object sender, KeyEventArgs e) 
    { 
     if (Key.Return == e.Key && 
      0 < (ModifierKeys.Shift & e.KeyboardDevice.Modifiers)) 
     { 
      var tb = (TextBox)sender; 
      var caret = tb.CaretIndex; 
      tb.Text = tb.Text.Insert(caret, Environment.NewLine); 
      tb.CaretIndex = caret + 1; 
      e.Handled = true; 
     } 
    } 
} 

public class Thing 
{ 
    public string Value { get; set; } 
} 

要考慮的另一件事是,如果插入鍵已被按下且您處於覆蓋輸入模式,您可能希望行爲不同。也許在這種情況下,下一個字符應該換成新行。但Visual Studio 2010中的資源編輯器似乎對插入鍵沒有反應(它也不會將文本顯示爲多行)。但我認爲給出這個例子,你可以擴展它以使用插入鍵。希望這有幫助,祝你好運!

+0

嗨,timmyl,非常感謝您的回答。 我已經採取了自己的方式,並試圖從文本框繼承,並解決我的問題,非常感謝你。 – yafeya 2011-02-13 14:51:32

6

設置TextWrapping爲Wrap和AcceptsReturn =真...

<DataGridTextColumn.EditingElementStyle> 
    <Style TargetType="TextBox"> 
    <Setter Property="TextWrapping" Value="Wrap" /> 
    <Setter Property="AcceptsReturn" Value="true" /> 
    </Style> 
</DataGridTextColumn.EditingElementStyle>