Combobox从不同的对象中选择了项目

时间:2013-10-28 15:28:13

标签: c# xaml mvvm winrt-xaml

我有一个组合框,并使用AccountType类填充列表,并且列表正在正确填充。

但是,当我将所选的Item属性绑定到Class account帐户时。在页面加载时,所选项目未更新。所有其他控件如文本框都会更新。

任何帮助都将受到高度赞赏。

视图

ComboBox ItemsSource="{Binding AllAccountTypes}" DisplayMemberPath="AccountTypeName" 
  SelectedValuePath="AccountTypeName" SelectedItem="{Binding SelectedAccount}" />

AccountType类

public class AccountType:IAccountType
{
    public string AccountTypeName { get; set; }
}

帐户类

public class Account: IAccount
{
    public int AccountNo { get; set; }
    public string AccountName { get; set; }
    public string AccountTypeName { get; set; }
    public int SubAccount { get; set; }
    public string Description { get; set; }
    public double Balance { get; set; }
    public string Note { get; set; }
    public bool Active { get; set; }

}

ViewModel中的选定帐户

    public IAccount SelectedAccount { get { return selectedAccount; }
        set { selectedAccount = value;  }
    }

2 个答案:

答案 0 :(得分:0)

首先,您的ViewModel需要提升PropertyChanged INotifyPropertyChanged事件。

其次,您的绑定应指定双向绑定:

<ComboBox ItemsSource="{Binding AllAccountTypes}" DisplayMemberPath="AccountTypeName" 
  SelectedValuePath="AccountTypeName" SelectedItem="{Binding SelectedAccount, Mode=TwoWay}" />

但第三,我认为这里的主要问题是您的组合框被绑定到AccountTypes列表(即IAccountType),但您希望所选项目是IAccount。但IAccount上没有IAccountType类型的属性。

因此,您需要将SelectedItem绑定到IAccountType属性,或将SelectedValue绑定到ViewModel上的字符串属性。 e.g:

<ComboBox ItemsSource="{Binding AllAccountTypes}" DisplayMemberPath="AccountTypeName"   
 SelectedItem="{Binding SelectedAccountType, Mode=TwoWay}"  />

并且在您的ViewModel中有一个绑定到的属性:

public IAccountType SelectedAccountType
{
    get { return selectedAccountType; }
    set
    {
        if (Equals(value, selectedAccountType)) return;
        selectedAccountType = value;
        OnPropertyChanged("SelectedAccountType");
    }
}

答案 1 :(得分:0)

这是因为您将SelectedItem绑定到IAccount对象,但是您从下拉列表中选择了一个字符串。

我会绑定到一个字符串,然后在setter中执行需要做的事情来设置SelectedAccount属性,如下所示:

    public string SelectedAccountName
    {
        get { return _selectedAccountName; }
        set
        {
            _selectedAccountName = value;
            SelectedAccount = AllAccounts.Where(x => x.AccountName == _selectedAccountName).First();
        }
    }

使用像这样的XAML(我添加了高度和宽度值,因此下拉列表不是很大):

<ComboBox Height="20" Width="100" ItemsSource="{Binding AllAccountTypes}" DisplayMemberPath="AccountTypeName" SelectedValuePath="AccountTypeName" SelectedItem="{Binding SelectedAccountName}" />
相关问题