WPF绑定行为

时间:2009-11-18 20:10:04

标签: wpf data-binding

我有这样的页面......

<Page x:Class="WPFTestRig.Page1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Page1">
<Grid>
    <StackPanel>
        <ComboBox Name="myBox" ItemsSource="{Binding Path=MyCollection}" DisplayMemberPath="Name" IsSynchronizedWithCurrentItem="True" 
                  SelectedItem="{Binding Path=SelectedEntryValue}" SelectedValuePath="Name" SelectedValue="{Binding Path=SelectedEntryValue}"/>
    </StackPanel>

</Grid>
</Page>

将代码隐藏为

 public partial class Page1 : Page
{
    private List<Entry> _myCollection;
    private string _selectedEntryValue;
    public Page1()
    {
        InitializeComponent();
        _myCollection = new List<Entry>();
        _myCollection.Add(new Entry { Name = "Test1", Id = 1 });
        _myCollection.Add(new Entry { Name = "Test2", Id = 2 });
        _myCollection.Add(new Entry { Name = "Test3", Id = 3 });

        _selectedEntryValue = "Test3";

        myBox.DataContext = this;
    }

    public List<Entry> MyCollection
    {
        get {
            return _myCollection;
        }
    }
    public string SelectedEntryValue
    {
        get {
            return _selectedEntryValue;
        }
        set { 
            _selectedEntryValue = value ;
        }
    }

}

public class Entry
{
    public string Name { get; set; }
    public int Id { get; set; }
}

当我在SelectedEntryValue属性的set属性上设置断点时,我看到它被调用两次,一次使用类型名称的字符串,如(MyTestApp.Entry),然后是实际选择的值

有人可以指出我应该做些什么让它正常工作?

非常感谢

2 个答案:

答案 0 :(得分:2)

您的问题是您不小心绑定了SelectedItemSelectedValue

您写的(为了便于阅读而重新格式化):

<ComboBox Name="myBox" ... SelectedValuePath="Name" ...
  SelectedItem="{Binding Path=SelectedEntryValue}"
  SelectedValue="{Binding Path=SelectedEntryValue}" />

删除SelectedItem绑定,您将获得所期望的行为。

答案 1 :(得分:1)

您正在看到该行为,因为您将其绑定到SelectedItemSelectedValue,因此它会执行两次。第一次绑定时,显示的属性尚未使用。