![](/img/trans.png)
[英]how to set combobox default value in wpf using binding in mvvm when manually setting combobox items
[英]How to set default text in the combobox using MVVM
我使用MVVM模式绑定WPF中的组合框。 我能够使用组合框绑定字符串列表,但我不知道如何在组合框中设置默认值。 好吧,我有一个名为“A”,“B”,“C”和“D”的名单。 现在我希望默认情况下“A”应该是默认值。
谢谢
<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;
}
}
我想说实现这一目标的最简单方法是绑定所选项目......
<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;
}
}
我认为你应该尝试使用ListItem。 ListItem具有Selected属性
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.