我有一个组合框:
<ComboBox Height="25" Width="150"
Name="EnvironmentComboBox"
ItemsSource="{Binding Path=SourceList}"
SelectedIndex="{Binding Path=SourceIndex}"
SelectionChanged="EnvironmentComboBox_SelectionChanged">
</ComboBox>
在代码隐藏中,我填充了SourceList:
public MainWindow()
{
InitializeComponent();
ConfigurationService.SetEnvironmentValues(ConfigurationService.DefaultEnvironment);
DataContext = this;
//SourceIndex = 0;
List<ComboBoxItem> source = new List<ComboBoxItem>
{
//new ComboBoxItem { Content = " - Select Environment - "},
new ComboBoxItem { Content = "PROD"},
new ComboBoxItem { Content = "CERT"},
new ComboBoxItem { Content = "DEV"},
};
SourceList = source;
}
这在很大程度上是基于我在这里找到的内容(包括_sourceIndex和_sourceList字段以及相应的属性):Setting a Combobox 's selected value without firing SelectionChanged event
我有一个SelectionChanged事件,它在更改ComboBox选择后触发:
private void EnvironmentComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (!(SourceIndex == 0))
{
String env = ((ComboBoxItem)((ComboBox)sender).SelectedValue).Content.ToString();
string message = $"Are you sure you want to change environment to {env}?\nAll unsaved work will be lost!";
const string caption = "Change Environment?";
MessageBoxResult userResponse = MessageBox.Show(message, caption,
MessageBoxButton.YesNo, MessageBoxImage.Warning);
if (userResponse == MessageBoxResult.Yes)
{
bool envChange = ConfigurationService.SetEnvironmentValues(env);
EnvironmentChangedMessage(envChange);
}
else
{
}
}
}
这里有两个问题。
首先,SelectionChanged事件似乎在应用程序启动时运行,我认为执行数据绑定可以解决这个问题(事实并非如此)所以我想,我将添加“-选择环境-“组合框项(您可以看到注解掉了),然后有那个条件!(SourceIndex == 0),以防止在选择“虚拟”值时,代码在ConfigurationService类中切换环境。但是,我真的只想在ConfigurationService类中加载PROD,并且在应用启动时也将其作为所选索引。因此,我不得不在应用启动前获取MessageBox,或者PROD不更改,因为它等于索引0。
第二,当用户单击MessageBox上的“No”时,我希望将所选组合框项的值还原为原始值。WPF ComboBox SelectedItem -更改为以前的值,但我不太确定如何在我的概念验证中实现它。我的SourceIndex setter中是否有提到的setter?如果有,在我的示例中CancelChange()在哪里?
如果您能在这两个问题上提供帮助,我将不胜感激。
3条答案
按热度按时间tmb3ates1#
为了避免默认值,我通常使用一个简单的布尔变量(Is_Loaded),如下所示
z6psavjg2#
其次,当用户单击MessageBox上的“否”时,我希望将选定组合框项的值还原为原始值。
为什么不使用一个变量来保存当前值,并在需要时将其检索回来呢?
xmakbtuz3#
如果我理解正确的话,你要实现的是:
第一个