将基本事件添加到动态添加的控件

时间:2017-12-06 13:58:46

标签: c# wpf

我有一些基本代码,当在Canvas上删除控件时,我需要用户能够通过简单的按键删除所述控件。

data class DataView(val id: String,
                     @get:JsonProperty("dayOfMonth") val monthDay: MonthDay)

data class MonthDay(val day: Int)

fun main(args: Array<String>) {
    val objectMapper = ObjectMapper()
            .registerKotlinModule()

    val dataView = DataView("someId", MonthDay(1))

    //{"id":"someId","dayOfMonth":{"day":1}}
    println(objectMapper.writeValueAsString(dataView))
}

我的代码看起来像那样。我的控件添加得很好,正好在我需要它的画布上。

事件处理程序什么都不做,我是否尝试通过lambda或通过传统调用将其添加到另一个方法。

我错过了什么?

1 个答案:

答案 0 :(得分:0)

以下步骤应足以使键盘输入正常工作:

  • 设置Focusable="True"
  • 处理MouseLeftButtonUp并在其中指定Keyboard.Focus
  • 设置Background以捕获鼠标事件
  • 处理重要事件

然后单击元素以对焦并使用您的键。另外,如果您不打算使用鼠标而只想通过按 tab 来关注它,则只需要Focusable和关键事件。

<Grid x:Name="grid1" KeyDown="grid1_KeyDown" Focusable="True" MouseLeftButtonUp="grid1_MouseLeftButtonUp" Background="Transparent">
</Grid>

焦点处理:

private void grid1_KeyDown(object sender, KeyEventArgs e)
{
    // whatever you plan to do
}

private void grid1_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
    Keyboard.Focus(sender as IInputElement);
}
相关问题