在我的組合框中,我有幾種不同的從數據庫加載的不同語言(通過綁定)。當組合框中的選擇更改爲不同的語言,並且用戶單擊確定按鈕時,我想要做一些簡單的操作,例如顯示一個新窗口。我想用WPF Commands(Name_CanExecute和Name_Executed)來實現。我昨天整天都在玩,並且無法使其工作。我是Wpf和MVVM模式的新手。當WPF組合框發生變化時觸發命令
如果有人能告訴我如何去做,我會非常感激。任何幫助表示讚賞。
在查看我的的.xaml代碼看起來是這樣的:
<UserControl x:Class="***.***.Modules.Localization.Views.LocalizationManager"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:***.***.Modules.Localization.Services"
xmlns:viewModels="clr-namespace:***.***.Modules.Localization.ViewModels"
Height="270" Width="230"
mc:Ignorable="d">
<UserControl.Resources>
<viewModels:LocalizationViewModelLocator x:Key="LocalizationViewModelLocator"/>
</UserControl.Resources>
<UserControl.DataContext>
<Binding Mode="OneWay" Path="LocalizationViewModel" Source="{StaticResource LocalizationViewModelLocator}"/>
</UserControl.DataContext>
<Grid Background="Gainsboro">
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<StackPanel Orientation="Horizontal" Grid.Row="1" Margin="10,10">
<TextBlock FontSize="13" FontFamily="Verdana" Text="Language: " />
<ComboBox Name="CboLanguageSelector" BorderThickness="1" MinWidth="105" ItemsSource="{Binding Languages}" />
<Button>OK</Button>
</StackPanel>
</Grid>
和我代碼視圖模型看起來是這樣的:
public class LocalizationViewModel : LocalizableViewModel
{
//the available languages from database are saved here
public ObservableCollection<string> Languages { get; private set; }
private readonly IDataAccessUnitOfWorkFactory dataAccessUnitOfWorkFactory;
public LocalizationViewModel(ILocalizationService localizationService,
IDataAccessUnitOfWorkFactory dataAccessUnitOfWorkFactory) : base(localizationService)
{
this.dataAccessUnitOfWorkFactory = dataAccessUnitOfWorkFactory;
LoadLanguagesFromCtlangTable();
}
/// <summary>
/// Get the available languages from the CTLANG table
/// </summary>
private void LoadLanguagesFromCtlangTable()
{
using (var unitOfWork = dataAccessUnitOfWorkFactory.Create())
{
string query = "SELECT languagename FROM ctlang ORDER BY languagename";
Languages = new ObservableCollection<string>(unitOfWork.OwEntities.Database.SqlQuery<string>(query));
}
}
//Implement Command_Execute and Command_CanExecute
}
[你如何處理MVVM中的ComboBox SelectionChanged?](http://stackoverflow.com/questions/950501/how-do-you-handle-a-combobox-selectionchanged-in-mvvm) – JanDotNet