wpf - 为什么这个 WPF ComboBox 没有显示选定的值?

标签 wpf combobox datatemplate selectedvalue

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

Window OnLoaded事件,我写了设置ItemsSource的代码:
cbo.ItemsSource = ser.GetCity().DefaultView;

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

问候

基肖尔

最佳答案

重置 ItemsSource 会弄乱选择。

此外,您正在设置 SelectedItem 和 SelectedIndex。您只想设置其中之一;如果两者都设置,则只有一个生效。

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

因此,要解决此问题,请在设置 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

关于wpf - 为什么这个 WPF ComboBox 没有显示选定的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2115256/

相关文章:

c# - 使用自定义控件绑定(bind)时如何允许默认值

c# - WPF 魔法字符串

WPF TreeView : Using ItemTemplateSelector and ItemContainerStyle Not Working At Same Time

c# - 转换为计算/绝对位置

.net - 使用 winform 而不是 WPF 的具体优势

.net - 如何用给定枚举中的所有项目填充XAML中的WPF组合框?

python - 使用 ComboboxSelected 对 tkinter Combobox 选择进行事件驱动管理

javascript - 如何从同名元素获取当前组合/文本框 ID(适用于新添加的元素)?

c# - (WPF) 如何使用每行中的按钮更改 listBox 中的按钮图像背景?

wpf - 我可以在 DataTemplate 中使用 DataTemplateSelector 吗?