簡體   English   中英

如何使用MVVM在組合框中設置默認文本

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM