双击

时间:2017-04-04 10:06:11

标签: c# wpf

我为数据库中的每个项目生成卡片。 现在我想添加一个编辑功能。所以我想,如果我双击TextBlock,它会更改为TextBox并具有相同的内容。

我的代码到现在为止:

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事件中的Visibility。但后来我遇到的问题是我不知道如何检测descContentBox。我检测到descContent(发件人为TextBlock)。但是如何检测生成的隐藏的descContentBox?

所以必须有另一种解决方案。有什么想法吗?

1 个答案:

答案 0 :(得分: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直接位于Panel,例如GridStackPanel,则上述示例应该有效:

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