无法将SelectedValue绑定到xaml中来自属性的WPF的组合框

时间:2013-01-02 05:36:53

标签: c# wpf binding

我不理解我遇到的绑定原则错误所以我很好奇:'TwoWay或OneWayToSource绑定无法在'Demo.ViewModel.MainWindowViewModel'类型的只读属性'CurrentUser'上工作。我的xaml正确绑定除了选择组合框的默认值'SelectedValue'。现在,如果我使用'SelectedValue =“1”'而不是代码手动执行此属性,那么此属性就可以了。最终目标是我想从数据库生成人员及其身份种子的列表,这很好。但我也想使用Windows登录,然后为用户设置自动默认值。如果该属性可以工作,这将有效,但我猜我需要知道更多的绑定规则。有点像WPF绑定只适用于某些类型和规则。我可以欺骗它并使'Person'类具有defaultuser然后引用,但似乎它应该是它自己的属性才能被很好地定义,我希望有人能够更好地了解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();
        }

2 个答案:

答案 0 :(得分:2)

所选值为two way binding,表示绑定属性为读取以更改所选值,但如果由于用户使用组合框而更改了选择,则属性为设置到该值。

所以有两种解决方案:

  • 以单向方式进行绑定:SelectedValue="{Binding Path=CurrentUser, Mode=OneWay}"
  • 在只读属性上创建一个setter,并正确处理用户的值更改。

正确的选择取决于您的申请。

答案 1 :(得分:0)

也许你忘了在当前用户属性中定义set方法? 其他的事情 - 你的类应该实现IProperty iNotify接口,但它不是错误的原因。