将ComboBox的SelectedItem设置为ListCollectionView中item的值

本文关键字:ListCollectionView item 的值 设置 ComboBox SelectedItem | 更新日期: 2023-09-27 18:09:27

我有一个ListCollectionView,它拥有一堆对象场景的项目。Scene中的一个属性是Location。

当我浏览ListCollectionView时,我想在视图的组合框中将Location属性的值设置为SelectedItem。每次转到ListCollectionView中的不同项目时,我都希望在组合框中显示新位置SelectedItem。

我知道如何使这个工作在一个普通的TextBox和TextBlock,但不是在一个组合框。

视图模型

public ListCollectionView SceneCollectionView { get; set; }
private Scene CurrentScene
{
    get { return SceneCollectionView.CurrentItem as Scene; }
    set
    {
        SceneCollectionView.MoveCurrentTo(value);
        RaisePropertyChanged();
    }
}
视图

<ComboBox  SelectedItem="{Binding SceneCollectionView/Location, UpdateSourceTrigger=PropertyChanged}" ItemsSource="{Binding AllLocations}}"/>

对于文本框,以下工作完美,但不适合组合框

 <TextBox Text="{Binding SceneCollectionView/Location, UpdateSourceTrigger=PropertyChanged}"/>

是否知道如何在ComboBox中为SelectedItem获得相同的行为。我对c#编程相当陌生

将ComboBox的SelectedItem设置为ListCollectionView中item的值

如果为ListCollectionView提供的集合中定义的所有Locations都存在于AllLocations属性中定义的Locations中,那么您的代码应该可以工作。

例如,下面的代码以及您当前在Xaml中定义的ComboBox如您所期望的那样工作:

Xaml:

<Grid>
    <ComboBox SelectedItem="{Binding SceneCollectionView/Location, UpdateSourceTrigger=PropertyChanged}" 
              ItemsSource="{Binding AllLocations}"/>
    <TextBox Text="{Binding SceneCollectionView/Location, UpdateSourceTrigger=PropertyChanged}"/>
    <Button  Content="SelectNext" Click="Button_Click"/>
</Grid>
代码:

    public ListCollectionView SceneCollectionView { get; set; }
    public List<string> AllLocations { get; set; }
    public MainWindow()
    {
        InitializeComponent();
        DataContext = this;
        var scenes = new List<Scene>();
        scenes.Add(new Scene { Location = "location1"});
        scenes.Add(new Scene { Location = "location2"});
        scenes.Add(new Scene { Location = "location3" });
        SceneCollectionView = new ListCollectionView(scenes);
        AllLocations = new List<string> { "location1", "location2", "location3" };
    }
    private void Button_Click(object sender, RoutedEventArgs e)
    {
        SceneCollectionView.MoveCurrentToNext();
    }

在上面的代码中,当您单击Button时,ComboBox.SelectedItemTextBox.Text都更改为SceneCollectionView中定义的下一个Item.Location

相关文章:
  • 没有找到相关文章