2012-03-15 103 views
2

我有一個包含多個ComboBoxes的WPF應用程序。某些組合框的ItemsSource綁定到對象列表。我想將每個組合框的文本屬性綁定到MyObject的某個屬性。每次用戶選擇MyListView中的某一行時,我都會更新MyObject的屬性,並且我還希望更新組合框的文本屬性。ComboBox中的綁定文本屬性不起作用

這對組合框的一個XAML:

<StackPanel Orientation="Vertical" x:Name="StackPanel_MyStackPanel"> 
    <ComboBox x:Name="comboBox_MyComboBox" 
       IsEditable="True" 
       ItemsSource="{Binding}" 
       Text="{Binding Path=MyProperty}" /> 
</StackPanel> 

在後面的代碼:

MyObject myObject = new MyObject(); 

// On the selection changed event handler of the MyListView, 
// I update the MyProperty of the myObject. 

this.StackPanel_MyStackPanel.DataContext = myObject; 

MyObject定義:

public class MyObject 
{ 
    private string _MyProperty; 

    public string MyProperty 
    { 
     get { return _MyProperty; } 
     set { _MyProperty = value; } 
    } 
} 

這是行不通的。 ...我不知道爲什麼。

+0

當你到底更新'myObject.MyProperty',之前或之後分配'這一點。 StackPanel_MyStackPanel.DataContext = myObject'? – Clemens 2012-03-15 12:28:17

+0

我想將組合框的Text屬性綁定到MyObject.MyProperty,ComboBox的ItemSource綁定到我的代碼後面的一些集合 - 我在這裏沒有提到什麼集合。 – 2012-03-15 12:29:54

+0

@Clemens當我分配this.StackPanel_MyStackPanel.DataContext = myObject – 2012-03-15 12:30:47

回答

1

你的數據類需要實現INotifyPropertyChanged

public class MyObject : INotifyPropertyChanged 
{ 
    public event PropertyChangedEventHandler PropertyChanged; 

    private string _MyProperty; 
    public string MyProperty 
    { 
     get { return _MyProperty;} 
     set 
     { 
      _MyProperty = value; 
      if (PropertyChanged != null) 
      { 
       PropertyChanged(this, new PropertyChangedEventArgs("MyProperty")); 
      } 
     } 
    } 
} 
0

對我來說,它的工作..

順便說一句,是的ItemsSource在ComboBox中的項目,則不需要設置在這裏

我增加了一個按鈕,測試它...這是我隱藏:

MyObject myObject = new MyObject(); 

/// <summary> 
/// Initializes a new instance of the <see cref="MainView"/> class. 
/// </summary> 
public MainView() 
{ 
    InitializeComponent(); 


    //On the selection changed event handler of the MyListView , I update the 
    //MyProperty of the myObject. 

    this.StackPanel_MyStackPanel.DataContext = myObject; 

} 

private void test_Click(object sender, System.Windows.RoutedEventArgs e) 
{ 
    MessageBox.Show(myObject.MyProperty); 
} 

我的XAML:

<StackPanel x:Name="StackPanel_MyStackPanel" 
      Width="Auto" 
      Height="Auto" 
      Orientation="Vertical"> 
    <ComboBox x:Name="comboBox_MyComboBox" 
       IsEditable="True" 
       Text="{Binding Path=MyProperty}" /> 
    <Button Name="test" Click="test_Click" Content="Show it" /> 
</StackPanel> 

我把你的012執行,但改名爲你的局部變量_MyProperty - 這是MyPropety