[英]How to set default text in the combobox using MVVM
I am binding a combobox in the WPF using MVVM pattern. 我使用MVVM模式绑定WPF中的组合框。 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".
好吧,我有一个名为“A”,“B”,“C”和“D”的名单。 Now I want that by default "A" should come as default value.
现在我希望默认情况下“A”应该是默认值。
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。 ListItem has Selected property
ListItem具有Selected属性
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.