【问题标题】:set SelectedItem of ComboBox to value of item in ListCollectionView将 ComboBox 的 SelectedItem 设置为 ListCollectionView 中项目的值
【发布时间】:2015-11-16 03:57:18
【问题描述】:

我有一个 ListCollectionView,其中包含一堆对象场景的项目。 Scene 中的属性之一是 Location。

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

我知道如何在常规的 TextBox 和 TextBlock 中进行这项工作,但在 ComboBox 中却不行。

视图模型

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# 编码还很陌生

【问题讨论】:

  • Location 属性的类型是什么?
  • 这是一个字符串属性

标签: c# wpf mvvm combobox selecteditem


【解决方案1】:

如果为您的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

【讨论】:

  • 这没有使用 MVVM
猜你喜欢
  • 2014-12-10
  • 1970-01-01
  • 2019-02-18
  • 2023-03-09
  • 1970-01-01
  • 1970-01-01
  • 2011-02-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多