WPF 组合框 SelectedIndex 不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17127492/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 09:01:01  来源:igfitidea点击:

WPF Combobox SelectedIndex Not Working

wpfcomboboxselecteditem

提问by coson

I have a WPF user control (FileSelectionView.xaml) with a combo box that displays data. My WPF looks like:

我有一个带有显示数据的组合框的 WPF 用户控件 (FileSelectionView.xaml)。我的 WPF 看起来像:

<ComboBox Width="250"
          HorizontalAlignment="Left"
          ItemsSource="{Binding Path=FileTypes}"
          SelectedItem="{Binding Path=FileType, Mode=TwoWay}" />

In my View Model file (FileSelectionViewModel.cs), I have a List that binds to this control that successfully works. The data looks like:

在我的视图模型文件 (FileSelectionViewModel.cs) 中,我有一个绑定到此控件的列表,该控件成功运行。数据看起来像:

<Please select a file>
File Type 1
File Type 2

I have tried to set the SelectedIndexproperty to 0 so that "<Please select a file>" shows up when the user control renders, but it is not working. It doesn't show anything, but when I click on the combo box, I do see all my items.

我试图将该SelectedIndex属性设置为 0,以便在用户控件呈现时显示“<请选择文件>”,但它不起作用。它没有显示任何内容,但是当我单击组合框时,我确实看到了我的所有项目。

Is there something I'm missing?

有什么我想念的吗?

采纳答案by Jasti

Instead of using SelectedIndex, After updating the ItemsSource, update the selected item with the following code from viewmodel

而不是使用SelectedIndex,更新后,使用ItemsSourceviewmodel中的以下代码更新所选项目

FileType = "Please select a value";

回答by denis morozov

IT works just fine, if you do it in XAML, I don't see it in your XAML, did you forget?

它工作得很好,如果你在 XAML 中这样做,我在你的 XAML 中看不到它,你忘记了吗?

 <ComboBox Width="250"
              HorizontalAlignment="Left"
              ItemsSource="{Binding Path=FileTypes}"
              SelectedItem="{Binding Path=FileType, Mode=TwoWay}" 
          SelectedIndex="0"/>

Note that only will work initially, then you'll have to reset it again when you need it.. via trigger, or code behind.

请注意,这只会在最初有效,然后您必须在需要时再次重置它……通过触发器或隐藏的代码。