I am binding a combobox in the WPF using MVVM pattern. I am able to bind a list of string with the combobox but I don't know how to set a default value in the combobox. Well I have a list of names which has "A","B","C" and "D". Now I want that by default "A" should come as default value.
Thanks
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ViewModel="clr-namespace:WpfApplication1.ViewModel"
Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
<ViewModel:NameViewModel></ViewModel:NameViewModel>
</Window.DataContext>
<Grid>
<ComboBox Height="23" Width="120" ItemsSource="{Binding Names}"/>
</Grid>
public class NameViewModel
{
private IList<string> _nameList = new List<string>();
public IList<string> Names { get; set; }
public NameViewModel()
{
Names = GetAllNames();
}
private IList<string> GetAllNames()
{
IList<string> names = new List<string>();
names.Add("A");
names.Add("B");
names.Add("C");
names.Add("D");
return names;
}
}
I'd say the easiest way to achieve this is bind the selected item as well...
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ViewModel="clr-namespace:WpfApplication1.ViewModel"
Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
<ViewModel:NameViewModel></ViewModel:NameViewModel>
</Window.DataContext>
<Grid>
<ComboBox
Height="23"
Width="120"
ItemsSource="{Binding Names}"
SelectedItem="{Binding SelectedName}"
/>
</Grid>
</Window>
public class NameViewModel
{
private IList<string> _nameList = new List<string>();
public IList<string> Names { get; set; }
public string SelectedName { get; set; }
public NameViewModel()
{
Names = GetAllNames();
SelectedName = "A";
}
private IList<string> GetAllNames()
{
IList<string> names = new List<string>();
names.Add("A");
names.Add("B");
names.Add("C");
names.Add("D");
return names;
}
}
I think you should try to use ListItem. ListItem has Selected property
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.