c# - 防止 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");
}
}
解决方案
推荐阅读
- rest - 用于保存和收藏项目的 RESTful API 端点结构
- android - Android 聊天分页会导致聊天屏幕向上跳到下一个分页
- git - 全局 Git 忽略不处理特定文件
- node.js - 在 Termux 中安装 sqlite3 时出错
- sql - Oracle 将使用 CTE 的工作 SQL 转换为过程
- c++ - 在同一行中声明和分配对象一些右值
- javascript - 水平和垂直条形图视图的按钮,但轴无法更改
- python - Python列表比较numpy优化
- flutter - 应用程序无法正常工作,因为
&/ 未处理的异常:“String”类型不是“FutureOr”类型的子类型 - typescript - ApolloServer 模式选项