【发布时间】:2012-12-16 12:58:39
【问题描述】:
我不理解我遇到的绑定原则错误,所以我很好奇:“TwoWay 或 OneWayToSource 绑定无法在“Demo.ViewModel.MainWindowViewModel”类型的只读属性“CurrentUser”上工作。我的 xaml 绑定正确,除了为组合框选择了默认值“SelectedValue”。现在,如果我使用 'SelectedValue = "1"' 而不是使用代码手动执行此属性,则该属性会很好。最终目标是我想从数据库中生成人员列表及其身份种子,这很好用。但我也想使用 Windows 登录然后为用户设置一个自动默认值。如果该属性有效,这将有效,但我猜我需要了解更多关于绑定规则的信息。有点像 WPF 绑定仅适用于某些类型和规则。我可以欺骗它并让“Person”类具有默认用户,然后引用它,但似乎它应该是它自己的属性来定义良好,我希望更擅长 WPF 绑定的人会知道我的问题。
XAML:
<ComboBox Height="30" Width="170" Margin="10" x:Name="combopersons"
FontSize="20"
ItemsSource="{Binding Path=People}"
DisplayMemberPath="FirstName"
SelectedValuePath="PersonId"
SelectedValue="{Binding Path=CurrentUser}" />
viewmodel 代码的部分 C# 代码:
ReadOnlyCollection<Person> _people;
string _curuser;
public string CurrentUser
{
get
{
if (_curuser == null)
{
_curuser = "1";
}
return _curuser;
}
}
public ReadOnlyCollection<Person> People
{
get
{
if(_people == null)
{
List<Person> persns = this.GetPeople();
_people = new ReadOnlyCollection<Person>(persns);
}
return _people;
}
}
List<Person> GetPeople()
{
ExpensesEntities ee = new ExpensesEntities();
return ee.tePersons.Select(x => new Person
{
PersonId = x.PersonID,
FirstName = x.FirstName
}).ToList();
}
【问题讨论】:
-
是
PersonID字符串还是整数?并且由于您在CurrentUser上没有设置器,您可能希望将您的BindingMode设置为OneWay -
这是一种可接受的方法,但是我希望以后能够更改组合框的值。我没有对此进行测试,但我假设我想设置我的属性并获得它。这解决了我希望用于我的应用程序的方法中的问题。