2012-05-21 63 views
3

我使用MVVM模式綁定WPF中的組合框。我能夠綁定與組合框的字符串列表,但我不知道如何在組合框中設置默認值。 那麼我有一個名單,其中有「A」,「B」,「C」和「D」。現在我希望默認情況下「A」應該作爲默認值。如何使用MVVM在組合框中設置默認文本

感謝

<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

Set SelectedItem via another view model property? – Alan

+0

是的Alan現在我明白了,謝謝。 – user1399377

回答

1

我認爲你應該嘗試使用ListItem。 ListItem已選定屬性

+0

是的,但WPF中的組合框也具有SelectedItem屬性。 – user1399377

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; 
    } 
} 
+0

這可能是最簡單的方法。應該提到的是,如果它不是很明顯,那麼如果你打算使用ComboBox的「SelectedItem」屬性,那麼綁定到的任何東西必須是ItemsSource集合中的一個項目,否則就不會顯示默認。 – Thelonias

+0

謝謝KDiTraglia,它對我來說工作得很好。 – user1399377

+0

@Ryan,是的,很明顯,選中的項目只有在該項目必須是ItemsSource集合中的項目時纔會起作用。 – user1399377