我使用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;
}
}
答案 0 :(得分:3)
我想说实现这一目标的最简单方法是绑定所选项目......
<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;
}
}
答案 1 :(得分:1)
我认为您应该尝试使用ListItem。 ListItem具有Selected属性