我有一个组合框,列表是使用 AccountType 类填充的,并且列表正在正确填充。
但是,当我将选定的项目属性绑定(bind)到类帐户的选定帐户时。在页面加载时,所选项目未更新。文本框等所有其他控件都在更新。
我们将不胜感激任何帮助。
查看
ComboBox ItemsSource="{Binding AllAccountTypes}" DisplayMemberPath="AccountTypeName"
SelectedValuePath="AccountTypeName" SelectedItem="{Binding SelectedAccount}" />
账户类型类
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; }
}
最佳答案
首先,您的 ViewModel
需要引发 INotifyPropertyChanged
的 PropertyChanged
事件。
其次,您的绑定(bind)应指定双向绑定(bind):
<ComboBox ItemsSource="{Binding AllAccountTypes}" DisplayMemberPath="AccountTypeName"
SelectedValuePath="AccountTypeName" SelectedItem="{Binding SelectedAccount, Mode=TwoWay}" />
但第三,我认为这里的主要问题是,您的组合框绑定(bind)到 AccountTypes 列表(即 IAccountType
),但您希望所选项目是 我账户
。但是 IAccountType
上没有 IAccount
类型的属性。
因此您需要将 SelectedItem 绑定(bind)到 IAccountType 属性,或将 SelectedValue 绑定(bind)到 ViewModel 上的字符串属性。例如:
<ComboBox ItemsSource="{Binding AllAccountTypes}" DisplayMemberPath="AccountTypeName"
SelectedItem="{Binding SelectedAccountType, Mode=TwoWay}" />
并且在您的 ViewModel 中有一个属性可以绑定(bind)到:
public IAccountType SelectedAccountType
{
get { return selectedAccountType; }
set
{
if (Equals(value, selectedAccountType)) return;
selectedAccountType = value;
OnPropertyChanged("SelectedAccountType");
}
}
关于c# - 组合框从不同的对象中选择的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19638790/