N.D
N.D

Reputation: 1049

Binding Text property in ComboBox not working

I have a WPF application containing several ComboBoxes. The ItemsSource of some of the comboboxes is bound to a list of objects. I want to bind a text property of each combobox to some property of MyObject. Each time a user selects some row in MyListView, I update the properties of MyObject, and I want the text properties of the comboboxes to update as well.

This is the XAML for one of the comboboxes:

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

In the code behind:

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;

the definition of MyObject:

public class MyObject
{
    private string _MyProperty;

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

This is not working.... and I don't know why.

Upvotes: 3

Views: 12594

Answers (2)

Clemens
Clemens

Reputation: 128013

Your data class needs to implement 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"));
            }
        } 
    } 
} 

Upvotes: 1

Felix C
Felix C

Reputation: 1775

For me it's working..

btw, ItemsSource is for the items in the combobox, you don't need to set it here

I added a button for testing it... this is my codebehind:

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);
}

My 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>

I took your implementation of MyObject, but renamed your local variable to _MyProperty - it was MyPropety

Upvotes: 0

Related Questions