views:

34

answers:

1

Hi guys. I have a WPF app with a listbox and a contentcontrol. The contentcontrol content is bound to the listbox and has a datatemplate that displays a textbox whose content is bound to a variable of the selected item in said listbox. So far, everything works well, i.e. when I select an item from the listbox the textbox content changes to the current value of the variable. However, if at runtime I change the value of the variable the textbox is not updated unless I select another listbox item and then select the original item again. Any ideas on what I am doing wrong or what I am missing here? I thought the value of the textbox would change automatically? Your help is much appreciated.

Here's the example (MainWindow.xaml)

< Grid> < ListBox Height="100" HorizontalAlignment="Left" Margin="12,105,0,0" x:Name="listBox1" VerticalAlignment="Top" Width="120" /> < ContentControl Height="120" HorizontalAlignment="Left" Margin="191,105,0,0" Name="contentControl1" VerticalAlignment="Top" Width="300" ContentTemplate="{DynamicResource MyDataTemplate}" Content="{Binding SelectedItem,ElementName=listBox1}"/> < Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="202,56,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" /> < /Grid>

The C# code:

    public MainWindow()
    {
        InitializeComponent();
        listBox1.Items.Add(new MyItem(32));
        listBox1.Items.Add(new MyItem(45));
        listBox1.Items.Add(new MyItem(5));
    }

    private void button1_Click(object sender, RoutedEventArgs e)
    {
        ((MyItem)listBox1.SelectedItem).Value = 4564654;
    }

An extra class:

public class MyItem
{
    public MyItem(Int32 Value)
    {
        this.Value = Value;
    }

    public Int32 Value { get; set; }
}

And the template:

Im sure I am missing something like notifying the UI of changes in the source or calling a refresh somehow. This is a much more simplified version of my real problem which includes controls and labels etc that must be refreshed when the source changes. Cheers :)

+2  A: 

You MyItem class probably needs to implement the INotifyPropertyChanged interface. When the Value property gets changed, call OnPropertyChanged("Value") to notify the interface that the value has changed and it needs to be redrawn.

public class MyItem : INotifyPropertyChanged
{
    public MyItem(Int32 Value)
    {
        this.Value = Value;
    }

    private Int32 _value;
    public Int32 Value 
    { 
        get { return _value; } 
        set { _value = value; OnPropertyChanged("Value"); }
    }
}
Rachel
Hi Rachel, thanks for the tip. Yes, I see where you are coming from, I've tested and it works, thanks for pointing me in the right direction. Thanks a lot!
Dogzilla