简体   繁体   中英

item value does not update in a bound wpf listbox with datatemplate set

It seems that I do something wring with the binding, but after a lot of tries and research I still didn't find why (all the examples I found were so similar to my implementation that I can't see what I did wrong), could you please help me with that?

I have a class called GlobalConfig which implements INotifyPropertyChanged and has a property called Name.

public class GlobalConfig : XmlSoftLinkSerializer, INotifyPropertyChanged
{
    private string _name;
    public string Name 
    { 
        get { return _name; } 
        set 
        {
            if (_name != value && PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs("Name"));
            _name = value;
        } 
    }

An ObservableCollection<GlobalConfig> is bound to a ListBox (by setting the DataContext property of the listbox), and I have this DataTemplate for the ListBox:

<DataTemplate>
     <TextBlock Text="{Binding Path=Name, UpdateSourceTrigger=PropertyChanged}" />
</DataTemplate>

I also have a user control called GlobalConfigUI which is bound to the DataContext of the listbox (using ElementName).

Everything works fine here, but when I change the Name of the config, nothing changes in the listbox... I checked and I know the PropertyChanged handler in the Name setter is called, also the object GlobalConfig is updated, but the listbox still displays the old name...

here is how the GlobalConfigUI is bound to the DataContext of the listbox:

<my:GlobalConfigUI x:Name="globalConfigUI1" DataContext="{Binding ElementName=settingsListBox, Path=SelectedValue, Mode=TwoWay}" />

and here is how the TextBox inside the GlobalConfigUI control is bound to the Name property:

<TextBox Name="configNameTextBox" Text="{Binding Path=Name, Mode=TwoWay, BindsDirectlyToSource=True}" MinWidth="380" />

I'm not completely new to WPF but I've used it only like 2 or 3 times, so I think there must be some kind of rooky mistake here, any hints?

As a first remark, change your TextBox binding by adding UpdateSourceTrigger=PropertyChanged . Also about BindsDirectlyToSource , I rarely use it. Remove it and check again

Also, change your implementation to

private string _name;
public string Name 
{ 
    get { return _name; } 
    set 
    {
        _name = value;
        if (_name != value && PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs("Name"));

    } 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM