使用 MVVM 在组合框中设置默认值

Clo*_*ock 2 c# wpf combobox mvvm

当应用程序首次使用 MVVM 模式加载时,我试图在组合框中设置一个默认值,并且看起来它始终未设置,当页面加载时,组合框始终为空。

这是我的 xaml:

    <ComboBox Grid.Row="0" Margin="10,0,0,0" Grid.Column="1" 
              SelectedItem="{Binding Path=JuiceOperations.SelectedItemOption, Mode=TwoWay}"
              SelectedIndex="{Binding Path=JuiceOperations.SelectedComboBoxOptionIndex, Mode=TwoWay}"
              SelectedValue="{Binding Path=JuiceOperations.SelectedComboBoxOptionIndex, Mode=TwoWay}"
              ItemsSource="{Binding Path=JuiceOperations.JuiceOptions}" />
Run Code Online (Sandbox Code Playgroud)

这是视图模型代码及其默认构造函数:

    public JuiceViewModel()
    {
        juiceOperations.SelectedComboBoxOptionIndex = 0;
        juiceOperations.SelectedItemOption = "Cola";
    }
Run Code Online (Sandbox Code Playgroud)

我试图设置组合框的默认值。

这就是属性的样子:

private List<string> juiceOptions = new List<string> { "Cola", "Sprite", "Fanta", "Pepsi" };

    private string selectedItemOption = string.Empty;

    private int selectedComboBoxOptionIndex = 0;

    public int SelectedComboBoxOptionIndex
    {
        get
        {
            return this.selectedComboBoxOptionIndex;
        }

        set
        {
            this.selectedComboBoxOptionIndex = value;
            this.OnPropertyChanged("SelectedComboBoxOptionIndex");
        }
    }

    public List<string> JuiceOptions
    {
        get
        {
            return this.juiceOptions;
        }

        set
        {
            this.juiceOptions = value;
        }
    }

    public string SelectedItemOption
    {
        get
        {
            return this.selectedItemOption;
        }

        set
        {
            this.selectedItemOption = value;
            this.OnPropertyChanged("SelectedItemOption");
        }
    }
Run Code Online (Sandbox Code Playgroud)

从组合框中选择一个项目时,选择会更新到模型和视图中,因此它可以按预期工作,但是当首次加载页面时,即使正在调用“SelectedComboBoxOptionIndex”和“SelectedItemOption”并且更新它们的值页面视图未更新,空字符串显示在组合框中,我预计会在其中看到“Cola”值,而不是空字符串。

有人可以解释我做错了什么以及我应该如何将默认的“可乐”值设置到组合框中吗?

mm8*_*mm8 5

仅将SelectedItem的属性绑定ComboBoxSelectedItemOption源属性,并将后者设置为视图模型中的字符串“Cola”。这应该有效:

<ComboBox Grid.Row="0" Margin="10,0,0,0" Grid.Column="1" 
          SelectedItem="{Binding Path=JuiceOperations.SelectedItemOption}"
          ItemsSource="{Binding Path=JuiceOperations.JuiceOptions}" />
Run Code Online (Sandbox Code Playgroud)
public JuiceViewModel()
{
    juiceOperations.SelectedItemOption = "Cola";
}
Run Code Online (Sandbox Code Playgroud)

不要混合SelectedItemSelectedIndex并且SelectedValue。你只需要一个。