【问题标题】:Setting ComboBox.SelectedItem at bind time?在绑定时设置 ComboBox.SelectedItem?
【发布时间】:2019-03-11 00:54:53
【问题描述】:

我在 DataTemplate 中有一个 ComboBox,它由 DataGrid 中的单元格模板选择器选择。

当 ComboBox 绑定到其 ItemsSource 时,如何将 SelectedItem 设置为零?通常只有一个项目,我希望它立即出现,而不必由用户选择。

我的 DataGrid 列如下所示:

<DataGridTemplateColumn Header="Qty Avl">
  <DataGridTemplateColumn.CellTemplateSelector>
    <selectors:PartAvailableSelector StrTemplate="{StaticResource PartAvailableAtStrTemplate}">
      <selectors:PartAvailableSelector.NetTemplate>
        <DataTemplate>
          <ComboBox ItemsSource="{Binding AltLocations}"
                    DisplayMemberPath="Name"
                    SelectedItem="0"
                    />
        </DataTemplate>
      </selectors:PartAvailableSelector.NetTemplate>
    </selectors:PartAvailableSelector>
  </DataGridTemplateColumn.CellTemplateSelector>
</DataGridTemplateColumn>

我的选择器具有 DataTemplate 属性,只是因为它更简单。我为这篇文章内联了 NetTemplate 模板。我通常在我的窗口资源中拥有它。

【问题讨论】:

    标签: wpf


    【解决方案1】:

    SelectedItem 将持有来自ItemsSource 的整个对象,要将0 项设置为选中您需要设置SelectedIndex="0" 或在ViewModel 中您需要将SelectedItem="{Binding SLocation}" 绑定到AltLocations[0]

     <ComboBox ItemsSource="{Binding AltLocations}"
                    DisplayMemberPath="Name"
                    SelectedIndex="0"
                    />
    

    或者

    <ComboBox ItemsSource="{Binding AltLocations}"
                    DisplayMemberPath="Name"
                    SelectedItem="{Binding SLocation}"
                    />
    

    Vm

    private Location sLocation
       public Location SLocation
        {
            get { return sLocation; }
            set
            {
                sLocation= value;
                OnPropertyChanged(new PropertyChangedEventArgs("SLocation"));
            }
        }
    

    //导演

    SLocation=AltLocations[0];

    【讨论】:

      猜你喜欢
      • 2011-10-14
      • 1970-01-01
      • 2010-10-25
      • 2010-10-26
      • 2018-07-27
      • 2012-07-19
      • 2012-06-17
      • 2011-01-13
      • 2011-02-08
      相关资源
      最近更新 更多