3

我正在使用 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;
   }
}
4

2 回答 2

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;
   }
}
于 2012-05-21T19:39:15.453 回答
1

我认为您应该尝试使用 ListItem。ListItem 具有 Selected 属性

于 2012-05-21T19:48:46.753 回答