确定Selector.SelectionChanged事件是否由用户启动

39 wpf

是否可以确定Selector.SelectionChanged事件是由用户启动还是以编程方式启动?

即我需要类似布尔"IsUserInitiated"属性的东西,只有在SelectionChanged因为用户使用鼠标或键盘更改了选择而引发事件时才是真的.

jim*_*415 22

简单的解决方法:

您可以创建一个临时禁用SelectionChanged事件的方法,并在需要以编程方式更改选择时调用它.

private void SelectGridRow( int SelectedIndex )
{
    myDataGrid.SelectionChanged -= myDataGrid_SelectionChanged;
    myDataGrid.SelectedIndex = SelectedIndex;

    // other work ...

    myDataGrid.SelectionChanged += myDataGrid_SelectionChanged;
}
Run Code Online (Sandbox Code Playgroud)


Dav*_*ret 15

这应该适用于大多数情况:

private void cboStatus_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    if (this.cboStatus.IsDropDownOpen)
    {
        //OPTIONAL:
        //Causes the combobox selection changed to not be fired again if anything
        //in the function below changes the selection (as in my weird case)
        this.cboStatus.IsDropDownOpen = false;

        //now put the code you want to fire when a user selects an option here
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 我试过这个,但是,如果用户使用键盘并点击Enter键进行选择,它对我不起作用.那时,IsDropDownOpen的值为false. (8认同)

Jus*_*tte 11

这是我自WinForms以来必须解决的一个问题.我希望在WPF中他们会添加一个布尔值来SelectionChangedEventArgs调用IsUserInitiated问题中提到的东西.当我想在数据加载和绑定到屏幕时忽略发生的任何事情时,我最常需要这个.例如,假设我基于SelectionChanged中的新值默认字段但是我希望用户能够覆盖此默认值,我只希望用户覆盖它,而不是屏幕重新加载时的应用程序.我仍然觉得我一直在做的是hacky,但我会发布它,因为我没有看到它提到.没有花哨的技巧,只是简单而有效.

1)创建一个名为_loading的类级别布尔值

private bool _loading;
Run Code Online (Sandbox Code Playgroud)

2)更新执行加载的方法中的布尔值

private async Task Load()
{
    _loading = true;
    //load some stuff
    _loading = false;
}
Run Code Online (Sandbox Code Playgroud)

3)随时使用布尔值

    private void SetDefaultValue(object sender, SelectionChangedEventArgs e)
    {
        if (!_loading) {
            //set a default value
        }
    }
Run Code Online (Sandbox Code Playgroud)


mle*_*may 5

取自http://social.msdn.microsoft.com,其中用户发布相同的问题

我认为我们无法区分SelectionChanged事件是由用户输入启动还是以编程方式启动.SelectionChanged事件并不关心.

通常,您现在可以始终以编程方式启动它,因为它是启动它的代码.

如果使用DataBinding绑定SelectedItem,则可以将NotifyOnSourceUpdated和NotifyOnTargetUpdated属性设置为True.您可以处理Binding.SourceUpdated和Binding.TargetUpdated事件.在大多数情况下,用户输入启动的更改从Target到Source.如果以编程方式启动更改,则会从Source转到Target.

我不知道它是否有帮助......

  • “通常,您始终可以知道它是否以编程方式启动,因为是您的代码启动了它。” 当 WPF 异步更改选择时,它是如何工作的? (2认同)
  • "如果使用DataBinding绑定SelectedItem,则可以将NotifyOnSourceUpdated和NotifyOnTargetUpdated属性设置为True.并且可以处理Binding.SourceUpdated和Binding.TargetUpdated事件." - 如果OP的最终目的是对用户发起的更改做出反应,而不是绑定启动的更改(不在事件本身上设置布尔标志),那么这就是要走的路. (2认同)