事件优先级:LostFocus 在 SelectionChange 之后调用

本文关键字:SelectionChange 之后 调用 LostFocus 优先级 事件 | 更新日期: 2023-09-27 18:33:40

晚上,我遇到了一个问题,即在LostFocus(文本框)事件之前调用SelectionChanged(TabControl)事件。

这是一个问题,因为 SelectionChanged 是在选项卡更改期间触发的,该实习生会将 ListView.SelectedIndex (TabControl>TabItem>ListView) 重置为 -1。

文本框使用 LostFocus 来更新/验证其依赖于 SelectedIndex 的 textbox.text。文本框中的文本是从List<string>存储/检索的,由于索引已更改,因此列表恰好超出范围。

我环顾四周,厌倦了一些东西,也是一种"黑客"的方法,并没有真正的帮助。

<TabControl SelectionChanged="SelectionChanged_Tab"
    <TabItem .../>
    <TabItem .../>
</TabControl>
<Grid>
   <Label .../>
   <TextBox Name="Name" LostFocus="Lost_Focus" .../>
</Grid>

法典:

private void SelectionChanged_Tab(object sender, SelectionChangedEventArgs e)
{
    if (e.Source is TabControl)
    {
        ListView1.SelectedIndex = -1;
        ListView2.SelectedIndex = -1;
    }
}
private void Lost_Focus(object sender, RoutedEventArgs e)
{
    TextBox textbox = sender as TextBox;
    int Index = ListView.SelectedIndex;
    if (string.IsNullOrEmpty(textbox.Text) || textbox.Text == "0")
    {
        textbox.Text = "0";
    }
    switch (textbox.Name)
    {
        case "Name":
            SomeList[Index].AProperty = textbox.Text;
            break;
    }
}

事件优先级:LostFocus 在 SelectionChange 之后调用

好的,所以从不同的角度思考问题之后,我决定简单地使 TabControl,一个可聚焦的事件,并在选择更改时简单地使其聚焦:

<TabControl SelectionChanged="SelectionChanged_Tab" Focusable="True"
    <TabItem .../>
    <TabItem .../>
</TabControl>

法典:

private void SelectionChanged_Tab(object sender, SelectionChangedEventArgs e)
{
    if (e.Source is TabControl)
    {
        ListView2.Focus();
        ListView1.SelectedIndex = -1;
        ListView2.SelectedIndex = -1;
    }
    if (ListView2.SelectedIndex == -1)
    {
        ListView1.Focus();
    }
}

我知道这不是最优雅的解决方案(在过程中或重构中),但这似乎可以完成工作。