2

我有一个绑定到 ObservableCollection<Source> 的组合框。在类中有 2 个属性 ID 和 Type,以及我将 ID 与 Type 结合的 ToString() 方法。当我更改组合框中的类型时,它仍然显示旧类型,但对象已更改。

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

看法:

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

源类:

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

当类型是视频时,当我将类型更改为调谐器时,组合框显示 01 视频,组合框仍然显示 01 视频,但它应该是 01 调谐器。但是当我调试对象类型更改为调谐器。

4

1 回答 1

4

这是完全正常的。ListBox不可能知道当或改变ToString时会返回不同的值。IDType

你必须以不同的方式来做。

<ListBox ItemsSource="{Binding ...}">
  <ListBox.ItemTemplate>
    <DataTemplate>
      <TextBlock>
        <TextBlock Text="{Binding ID}"/>
        <TextBlock Text=" "/>
        <TextBlock Text="{Binding Type}"/>
      </TextBlock>
    </DataTemplate>
  </ListBox.ItemTemplate>
</ListBox>
于 2012-12-06T10:32:21.027 回答