2009-11-18 59 views
1

我有這樣的網頁...WPF綁定行爲

<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屬性的設置屬性,我看到它被調用兩次,一次與類型名稱的字符串(MyTestApp.Entry),然後實際選定的值

有人可以指出我應該怎麼做才能正常工作嗎?

千恩萬謝

回答

1

你看到這種行爲,因爲你把它綁定到兩個SelectedItemSelectedValue,因此執行兩次。第一次被綁定時,顯示的屬性還沒有被使用。

2

你的問題是你不小心綁定了SelectedItemSelectedValue

你寫(重新格式化爲可讀性):

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

取出SelectedItem結合,你會得到你所期望的行爲。