首页 > 解决方案 > 防止 Bound ComboBox 在应用程序启动时触发 SelectionChanged 事件

问题描述

我有ComboBox一个ViewModel Items Source List.

ComboBox也有SelectionChanged Event一个。

我希望事件仅在用户单击ComboBox并选择新项目时触发。

但是,当加载绑定项目并且以编程方式选择默认项目时,该事件会在应用程序启动时触发。


XAML

<ComboBox x:Name="cboDisplay"
          ItemsSource="{Binding Display_Items}"
          SelectedValue="{Binding Display_SelectedItem, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
          VerticalAlignment="Top"
          HorizontalAlignment="Left" 
          Margin="10,10,0,0"
          Height="22" 
          Width="100" 
          SelectionChanged="cboDisplay_SelectionChanged" />

C#

private void cboDisplay_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
      MessageBox.Show("Event Fired");
}

视图模型

public class MainViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged = delegate { };
    private void OnPropertyChanged(string prop)
    {
        PropertyChangedEventHandler handler = PropertyChanged;

        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(prop));
        }
    }


    public MainViewModel()
    {
        // Default Item at Startup
        Display_SelectedItem = "Windowed";
    }


    // Items Source
    //
    private List<string> _Display_Items = new List<string>()
    {
        "Fullscreen",
        "Windowed"
    };  
    public List<string> Display_Items
    {
        get { return _Display_Items; }
        set
        {
            _Display_Items = value;
            OnPropertyChanged("Display_Items");
        }
    }


    // Selected Item
    //
    private string _Display_SelectedItem { get; set; }
    public string Display_SelectedItem
    {
        get { return _Display_SelectedItem; }
        set
        {
            if (_Display_SelectedItem == value)
            {
              return;
            }

            _Display_SelectedItem = value;
            OnPropertyChanged("Display_SelectedItem");
        }
    }

标签: c#wpfxamlmvvmcombobox

解决方案


推荐阅读