简体   繁体   中英

ObservableCollection bound to Combobox ToString methode doesn't update

I have a Combobox that is bound to an ObservableCollection<Source>. In the class there are 2 properties ID and Type, and the ToString() method where i combine the ID with the Type. When i change the type in the combobox it still shows the old type but the Object is changed.

public partial class ConfigView : UserControl,INotifyPropertyChanged
{

    public ObservableCollection<Source> Sources
    {
        get { return _source; }
        set { _source = value;
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs("Sources"));
        }
    }


    public ConfigView()
    {
        InitializeComponent();
        this.DataContext = this;
        Sources = new ObservableCollection<Source>();
    }


    public ChangeSelected(){
         Source test = lstSources.SelectedItem as Source;
         test.Type = Types.Tuner;
    }
}

View:

<ListBox x:Name="lstSources" Background="Transparent" Grid.Row="1" SelectionChanged="lstSources_SelectionChanged" ItemsSource="{Binding Sources, Mode=TwoWay}" />

Source Class:

public enum Types { Video, Tuner }

    [Serializable]
    public class Source: INotifyPropertyChanged
    {

        private int id;

        public int ID
        {
            get { return id; }
            set { id = value;
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs("ID"));
            }
        }

        private Types type;

        public Types Type
        {
            get { return type; }
            set { type = value;
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs("Type"));
            }
        }


        public Source(int id, Types type)
        {
            Type = type;
            ID = id;
        }

        public override string ToString()
        {
            return  ID.ToString("00") + " " +  Type.ToString();
        }

        public event PropertyChangedEventHandler PropertyChanged;
    }

When the Type is Video the Combobox shows 01Video when i change the type to Tuner the Combobox still shows 01Video but it should be 01Tuner. But when i debug the Object type is changed to Tuner.

That's perfectly normal. The ListBox can't possibly knows that ToString will return a different value when ID or Type changes.

You got to do it differently.

<ListBox ItemsSource="{Binding ...}">
  <ListBox.ItemTemplate>
    <DataTemplate>
      <TextBlock>
        <TextBlock Text="{Binding ID}"/>
        <TextBlock Text=" "/>
        <TextBlock Text="{Binding Type}"/>
      </TextBlock>
    </DataTemplate>
  </ListBox.ItemTemplate>
</ListBox>

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