2012-03-15 7 views
2

私はいくつかのComboBoxesを含むWPFアプリケーションを持っています。一部のコンボボックスのItemsSourceは、オブジェクトのリストにバインドされています。私は各コンボボックスのテキストプロパティをMyObjectのプロパティにバインドしたいと思います。ユーザーがMyListViewの行を選択するたびに、MyObjectのプロパティが更新され、コンボボックスのテキストプロパティも更新されます。ComboBoxのTextプロパティをバインドできません

これは、コンボボックスのいずれかのXAMLです:

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の定義:背後にあるコードで

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

public class MyObject 
{ 
    private string _MyProperty; 

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

これが機能していません。 ...なぜか分からない。

それが働いている私にとって
+0

あなたが 'これを割り当てる前または後に、正確にあなたが、' myObject.MyProperty'を更新しないとき。 StackPanel_MyStackPanel.DataContext = myObject'? – Clemens

+0

ComboBoxのTextプロパティをMyObject.MyPropertyにバインドしたいのですが、ComboBoxのItemSourceはコードの背後にあるいくつかのコレクションにバインドされています。 –

+0

@Clemens私はthis.StackPanel_MyStackPanel.DataContext = myObjectを割り当てた後 –

答えて

1

た:

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は、コンボボックス内の項目のためである、あなたはここで

それを設定する必要はありません、私はそれをテストするためのボタンを追加しました...これがあります私の分離コード:

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に、ローカル変数に改名 - それはあなたのデータクラスがINotifyPropertyChangedを実装する必要がありMyPropety

関連する問題