I have developed a test application for language localization. The application contain one comboBox and one label. The comboBox contain different languages. Based upon the selection of languages the label text culture should change. In the solution I have added resource files (.resx files),and I have bind them with label. And the solution contain one xml file which contain languages. So I have bind the comboBox successfully. But unable to write the code for when there is change in combobox value the label textshould change in MVVM Pattern. Below code I have tried. Please someone help me in this.
What I have tried:
This is the model Language.cs
public class Language
{
public Language(XElement element)
{
Id = (int)element.Attribute("ID");
Name = (string)element.Element("Name");
CultureCode = (string)element.Element("culture");
}
public int Id { get; }
public string Name { get; }
public string CultureCode { get; }
}
This is the ViewModel.cs
public class LanguageViewModel: ViewModelBase
{
public IReadOnlyList<Model.Language> Languages { get; } = LoadLanguages();
private static IReadOnlyList<Model.Language> LoadLanguages()
{
XDocument doc = XDocument.Load("Languages.xml");
return doc.Root.Elements("Language").Select(el => new Model.Language(el)).ToList();
}
}
This is the viewModelBase.cs
public class ViewModelBase : INotifyPropertyChanged
{
protected void OnPropertyChanged<T>(Expression<Func<T>> expression)
{
var property =(MemberExpression)expression.Body;
}
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this,new PropertyChangedEventArgs(name));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
This is the mainWindow.xaml
<Grid>
<Label Content="{x:Static Resources:Resources.lblText}" HorizontalAlignment="Left" Margin="194,100,0,0" VerticalAlignment="Top" Height="36" Name="lblName"/>
<ComboBox x:Name="cmName" Height="30" Width="150" ItemsSource="{Binding Path=Languages}" DisplayMemberPath="Name" />
</Grid>
And this is MainWindow.xaml.cs
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new ViewModel.LanguageViewModel();
}
}
And This is the Languages.xml
<?xml version="1.0" encoding="utf-8" ?>
<LANGUAGES>
<LANGUAGE ID="1">
<Name>English</Name>
<Culture>en-US</Culture>
</LANGUAGE>
<LANGUAGE ID="2">
<Name>German</Name>
<Culture>de-DE</Culture>
</LANGUAGE>
<LANGUAGE ID="3">
<Name>Chines</Name>
<Culture>zh-CN</Culture>
</LANGUAGE>
</LANGUAGES>