以下是使用更多 MVVM 方法执行此操作的方法:
视图模型:
public class MyViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public Location SelectedcbDefaultLocationListItem = new Location { LocationName = "---Select One---", LocationID = -1 };
public ObservableCollection<Location> LocationList { get; set; }
private int _selectedLocationID;
/// <summary>
/// Get/Set the SelectedLocationID property. Raises property changed event.
/// </summary>
public int SelectedLocationID
{
get { return _selectedLocationID; }
set
{
if (_selectedLocationID != value)
{
_selectedLocationID = value;
RaisePropertyChanged("SelectedLocationID");
}
}
}
/// <summary>
/// Constructor
/// </summary>
public MyViewModel()
{
LocationList = new ObservableCollection<Location>();
LocationList.Add(new Location() { LocationID = 1, LocationName = "Here" });
LocationList.Add(new Location() { LocationID = 2, LocationName = "There" });
LocationList.Insert(0, SelectedcbDefaultLocationListItem);
SelectedLocationID = SelectedcbDefaultLocationListItem.LocationID;
}
/// <summary>
/// Resets the selection to the default item.
/// </summary>
public void ResetSelectedItem()
{
SelectedLocationID = SelectedcbDefaultLocationListItem.LocationID;
}
private void RaisePropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
代码背后:
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow
{
public MyViewModel ViewModel { get; private set; }
public MainWindow()
{
InitializeComponent();
ViewModel = new MyViewModel();
DataContext = ViewModel;
}
private void ResetButton_Click(object sender, System.Windows.RoutedEventArgs e)
{
ViewModel.ResetSelectedItem();
}
}
XAML:
<Window xmlns:xctk="http://schemas.xceed.com/wpf/xaml/toolkit" x:Class="StackOverflow.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:system="clr-namespace:System;assembly=mscorlib"
Title="MainWindow" Height="350" Width="525">
<Grid>
<StackPanel>
<ComboBox ItemsSource="{Binding LocationList, Mode=OneWay}" DisplayMemberPath="LocationName" SelectedValuePath="LocationID" SelectedValue="{Binding SelectedLocationID, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
<Button Click="ResetButton_Click" Content="Reset" Margin="5" HorizontalAlignment="Right" />
</StackPanel>
</Grid>
</Window>
通常会使用命令而不是在后面的代码中调用 reset 方法。但是由于您没有使用完整的 MVVM 方法,这应该就足够了。