2010-01-22 75 views
0
<CombobBox x:Name="cbo" 
      Style="{StaticResource ComboStyle1}" 
      DisplayMemberPath="NAME" 
      SelectedItem="{Binding Path=NAME}" 
      SelectedIndex="1"> 
    <ComboBox.ItemTemplate> 
    <DataTemplate> 
     <Grid> 
     <TextBlock Text="{Binding Path=NAME}"/> 
     </Grid> 
    </DataTemplate> 
    </ComboBox.ItemTemplate> 
</ComboBox> 

WindowOnLoaded事件,我写的代码来设置ItemsSource为什么这个WPF组合框不显示选定的值?

cbo.ItemsSource = ser.GetCity().DefaultView; 

虽然装载的窗户,我可以看到最初的第一项加载,但在同一时间,它会清除显示的项目。我被困在这种情况下,任何帮助表示赞赏。

问候

回答

4

快速回答:从代码隐藏设置SelectedIndex = 1

看来,XAML中的代码首先执行(InitializeComponent()方法),它设置了SelectedIndex = 1,但尚未指定ItemsSource!所以SelectedIndex不会影响! (请记住,你不能指定ItemsSourceInitializeComponent()

所以,你必须设置ItemsSource后手动设置SelectedIndex = 1


你应该这样做:

XAML

  <ComboBox x:Name="cbo" 
         Style="{StaticResource ComboStyle1}"> 
       <ComboBox.ItemTemplate> 
        <DataTemplate> 
         <Grid> 
          <TextBlock Text="{Binding Path=NAME}"/> 
         </Grid> 
        </DataTemplate> 
       </ComboBox.ItemTemplate> 
      </ComboBox> 

代码

 cbo.ItemsSource = ser.GetCity().DefaultView; 
    cbo.SelectedIndex = 1; 

或者这样:

XAML

  <ComboBox x:Name="cbo" Initialized="cbo_Initialized" 
         Style="{StaticResource ComboStyle1}"> 
       <ComboBox.ItemTemplate> 
        <DataTemplate> 
         <Grid> 
          <TextBlock Text="{Binding Path=NAME}"/> 
         </Grid> 
        </DataTemplate> 
       </ComboBox.ItemTemplate> 
      </ComboBox> 

代码

private void cbo_Initialized(object sender, EventArgs e) 
    { 
     cbo.SelectedIndex = 1; 
    } 

另外请注意,我已经删除DisplayMemberPath="NAME"因为你不能同时设置DisplayMemberPathItemTemplate在同一时间。而且,请使用SelectedItemSelectedIndex,而不是两者。

+1

非常感谢您的意见。 – 2010-01-22 09:09:32

2

重置的ItemsSource将陷入困境的选择。

此外,您正在设置SelectedItem和SelectedIndex。你只想设置其中的一个;如果您同时设置,则只有一个生效。

另外,您的SelectedItem声明可能是错误的。 SelectedItem="{Binding NAME}"将查找与环境(可能是Window级别)DataContext的NAME属性值相等的项目。这只有在ComboBox.ItemsSource是一个字符串列表时才有效。由于你的ItemTemplate工作,我假设ComboBox.ItemsSource实际上是一个城市对象的列表。但是你告诉WPF SelectedItem应该是一个字符串(一个名字)。该字符串永远不会等于任何城市对象,因此结果将不会被选中。

因此,要解决这个问题,设置的ItemsSource,要么设置或的SelectedItem的SelectedIndex,这取决于你的需求和你的数据模型后:

cbo.ItemsSource = ser.GetCity().DefaultView; 
cbo.SelectedIndex = 1; 
// or: cbo.SelectedItem = "Wellington"; // if GetCity() returns strings - probably not 
// or: cbo.SelectedItem = City.Wellington; // if GetCity() returns City objects 
+0

+1对于重置ItemsSource会弄乱选择。我正在刷新我的ItemsSource,搞砸了绑定。 – 2012-12-26 17:00:50

相关问题