2017-04-04 57 views
0

Im爲數據庫中的每個項目生成卡片。 現在我想添加一個編輯功能。所以我想,如果我雙擊一個TextBlock,它將更改爲TextBox並具有相同的內容。使用生成的TextBox更改生成的TextBlock雙擊

我的代碼到現在爲止是:

private void TextBlock_MouseDown(object sender, MouseButtonEventArgs e) 
    { 
     if (e.LeftButton == MouseButtonState.Pressed && e.ClickCount == 2) 
     { 
      string test = (sender as TextBlock).Text; 
      (sender as TextBlock).Visibility = Visibility.Hidden; 

      TextBox descContentBox = new TextBox(); 
      descContentBox.TextWrapping = TextWrapping.Wrap; 
      descContentBox.Text = test; 
      descContentBox.Opacity = .68; 

     } 
    } 

但我想這不會工作。因爲我在另一個函數中生成TextBlock等。

我的第二次嘗試是:

private void LoadRoles() 
    [...] 
    TextBlock descContent = new TextBlock(); 
    descContent.Opacity = .68; 
    descContent.TextWrapping = TextWrapping.Wrap; 
    descContent.Text = reader[2].ToString(); 

    TextBox descContentBox = new TextBox(); 
    descContentBox.TextWrapping = TextWrapping.Wrap; 
    descContentBox.Text = descContent.Text; 
    descContentBox.Opacity = .68; 
    descContentBox.Visibility = Visibility.Hidden; 

,然後更改在MouseDown事件中的可見性。但後來我有問題,我不知道如何檢測descContentBox。我檢測到descContent(發件人爲TextBlock)。但如何檢測生成的隱藏descContentBox?

所以必須有另一種解決方案。有任何想法嗎 ?

+0

您正在創建新的「文本框」,但未將其附加到「持有者」(父控件)中。 –

+0

是因爲我的持有者(生成的StackPanel)是在LoadRoles方法中定義的。所以我無法從MouseDown事件訪問它。 –

回答

2

TextBlock位於某種父母面板中。你可以得到這一個參考,並添加TextBox到它,比如:

private void TextBlock_MouseDown(object sender, MouseButtonEventArgs e) 
{ 
    if (e.LeftButton == MouseButtonState.Pressed && e.ClickCount == 2) 
    { 
     TextBlock txt = sender as TextBlock; 
     Panel panel = txt.Parent as Panel; 
     if (panel != null) 
     { 
      txt.Visibility = Visibility.Collapsed; 
      int index = panel.Children.IndexOf(txt); 

      TextBox descContentBox = new TextBox(); 
      descContentBox.TextWrapping = TextWrapping.Wrap; 
      descContentBox.Text = "test"; 
      descContentBox.Opacity = .68; 
      panel.Children.Insert(index, descContentBox); 
     } 

    } 
} 

如果TextBlock直接坐落在上面的例子應該工作PanelGridStackPanel

<StackPanel> 
    <TextBlock MouseDown="TextBlock_MouseDown" Text="edit..." /> 
</StackPanel> 
+0

問題是,StackPanel也生成了。 該代碼太長,但這裏是我生成的控件的代碼: https://pastebin.com/HrPs9RVU –

+0

那麼, StackPanel是否「生成」有什麼區別? – mm8

+1

哦對不起。這是清晨,我沒有檢查我們的代碼。 Nvm它的工作現在thx爲您的幫助:) –