【问题标题】:WPF - Fire comboBox SelectedIndexChanged only from user clickWPF - 仅从用户单击触发组合框 SelectedIndexChanged
【发布时间】:2015-05-12 09:09:33
【问题描述】:

我想阻止在 UI 加载时触发 ComboBox_SelectionChanged 事件。只有当用户在组合框中进行一些更改时才会发生这种情况。

为此,我在 .xam.cs 文件中编写了以下内容。

  private void myComboBox_SelectionChanged(object sender,   SelectionChangedEventArgs e)
      {
        ComboBox cb = (ComboBox)sender;
        if (!cb.IsFocused)
        {
            return;
        }
        else
           ViewModel.OnPropertyChanged("MyProperty");
     }

但这甚至不会在用户进行更改时触发事件。 我哪里出错了?

我知道 stackoverflow 中有一个类似的问题。但是其中的解决方案对我不起作用。请帮忙。

【问题讨论】:

  • 您是否遵循 MVVM 设计模式?如果是这样,您为什么要处理 SelectionChanged 事件。如果此组合中有一个 Command 属性,我建议将其绑定到您的 ViewModel 中的属性。
  • Command 属性不适用于组合框...对吗?是的,我查过了,它不存在:(
  • 使用 SelectedValue 属性,
  • 绑定到 ViewModel 中的属性

标签: c# wpf combobox


【解决方案1】:

找到了解决方案。 我们只需要将 Selection_Changed 事件与 PreviewMouseDown 事件结合起来。

could the SelectionChanged event in WPF be handled only for user interaction?

【讨论】:

    【解决方案2】:

    这是一个 XAML 示例:

    <av:ComboBox x:Name="cmbChargeUnit" HorizontalAlignment="Left" Margin="548,15,0,0" Width="187" ItemsSource="{av:Binding ChargeUnits}" DisplayMemberPath="ChargeUnitDescription" SelectedValue="{Binding SelectedChargeUnit}" VerticalAlignment="Top" Background="#FFCBCBCB" Height="20" IsSynchronizedWithCurrentItem="True"  SelectedIndex="0"  BorderBrush="#FF7070CB"/>
    

    虚拟机:

    public ChargeUnit SelectedChargeUnit
        {
            get { return _selectedChargeUnit; }
            set
            {
                _selectedChargeUnit = value;
                OnPropertyChanged("SelectedChargeUnit");
                if (SelectedAttributeId != null)//Only Load when an attribute is entered
                {
                    LoadRates();
                }
            }
        }
    

    【讨论】:

    • 它怎么会变成 null ?我有这样的财产。但它总是设置为某个值。仅当用户更改组合框中的项目时才会更改
    • 这部分是在调用方法加载使用该属性的费率之前检查我的 ViewModel 上的另一个属性,就像我说的那样,这只是一个示例,当您在组合框中选择项目时,它将点击 Set 访问器,然后您可以调用一个方法,该方法将在每次此值更改时调用。
    • 我也已经试过了。这也是一样的。在页面加载时触发组合框选择更改事件
    • 它不应该触发一个事件,因为不应该有一个事件?只是财产?选择组合中的项目时,该属性应点击其 Set 访问器。当窗口加载时,它将访问它的 Get 访问器。
    猜你喜欢
    • 2011-11-28
    • 1970-01-01
    • 2012-11-06
    • 2011-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多