【问题标题】:ComboBox in my WPF DataGrid won't display any items我的 WPF DataGrid 中的 ComboBox 不会显示任何项目
【发布时间】:2011-12-01 19:06:34
【问题描述】:

我有一个包含 DataGrid 的 WPF 用户控件。此 DG 包含多个列,包括用于状态的 ComboBox。状态列表作为属性填充并存储在我的 ViewModel 中。

我正在尝试将 StateList 属性绑定到我的组合框的 ItemsSource,但是当我运行表单并尝试编辑 DG 时,组合框不包含任何值,组合框为空。

这是用户控件的 XAML。

<UserControl x:Class="myproject.View.ucContactView"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         mc:Ignorable="d" d:DesignHeight="475" d:DesignWidth="977">
<UserControl.Resources>
    <ResourceDictionary Source="/Templates/MyResourceDictionary.xaml"/>
</UserControl.Resources>
<Grid DataContext="{Binding ViewModel}">
    <DataGrid AutoGenerateColumns="False" ItemsSource="{Binding AddressCollectionViewSource.View}">
        <DataGridTemplateColumn Header="State" Width="160">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding StateDescription}"/>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
            <DataGridTemplateColumn.CellEditingTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                        <ComboBox Name="cboState"
                                  SelectedValuePath="StateKey"
                                  ItemTemplate="{StaticResource dtStateTemplate}"
                                  ItemsSource="{Binding StateList}" 
                                  SelectedItem="{Binding StateKey, Mode=TwoWay}"
                                  Width="100" />
                    </StackPanel>
                </DataTemplate>
            </DataGridTemplateColumn.CellEditingTemplate>
        </DataGridTemplateColumn>
    </DataGrid>
</Grid>
</UserControl>

奇怪的是,如果我在这个用户控件上用完全相同的组合框创建另一个组合框,这个组合框会按预期工作。

<!-- this works as long as it's not in the DG -->
<StackPanel Height="126" HorizontalAlignment="Left" Margin="766,275,0,0" Name="stackPanel1" VerticalAlignment="Top" Width="200" >
    <ComboBox Name="cboState2"
          SelectedValuePath="StateKey"
          ItemTemplate="{StaticResource dtStateTemplate}"
          ItemsSource="{Binding StateList}" 
          SelectedItem="{Binding StateKey, Mode=TwoWay}"
          Width="100" />
</StackPanel>

为什么 DG 中的组合框不显示来自 StateList 属性的值?为什么单独的组合框可以正常工作?

【问题讨论】:

  • 为什么不能使用DataGridComboBoxColumn

标签: wpf mvvm datagrid


【解决方案1】:

它不起作用,因为您的 ComboBox 正在寻找 StateList 作为 DataGridDataContext 的属性。也就是说,当它需要绑定到ViewModel.StateList 时,它会尝试绑定到ViewModel.AddressCollectionViewSource.View.StateList。在调试时检查你的输出窗口,我敢打赌你会看到Could not find property StateList on object AddressCollectionViewSource (or maybe ICollection)的绑定错误。

试试这个:

<ComboBox Name="cboState2" 
      SelectedValuePath="StateKey" 
      ItemTemplate="{StaticResource dtStateTemplate}" 
      ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor,
            AncestorType={x:Type DataGrid}}, Path=DataContext.StateList}"  
      SelectedItem="{Binding StateKey, Mode=TwoWay}" 
      Width="100" /> 

【讨论】:

    【解决方案2】:

    如果您的视图模型是窗口中的一个属性,您可以这样做

    ItemsSource="{Binding RelativeSource={RelativeSource AncestorType={x:Type Window}}, Path=ViewModel.StateList, Mode=OneWay}"
    


    <Window x:Class="WpfStackOverflowSpielWiese.Window2"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            Title="Window2"
            Height="300"
            Width="300"
            x:Name="window">
    
      <Grid DataContext="{Binding ElementName=window, Path=ViewModel}">
    
        <DataGrid x:Name="grid"
                  AutoGenerateColumns="False"
                  ItemsSource="{Binding AddressCollectionViewSource, Mode=OneWay}">
    
          <DataGrid.Columns>
            <DataGridTemplateColumn Header="State"
                                    Width="160">
    
              <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                  <TextBlock Text="{Binding StateKey}" />
                </DataTemplate>
              </DataGridTemplateColumn.CellTemplate>
    
              <DataGridTemplateColumn.CellEditingTemplate>
                <DataTemplate>
                  <StackPanel Orientation="Horizontal">
                    <ComboBox Name="cboState"
                              SelectedValuePath="StateKey"
                              ItemsSource="{Binding RelativeSource={RelativeSource AncestorType={x:Type Window}}, Path=ViewModel.StateList, Mode=OneWay}"
                              SelectedItem="{Binding StateKey, Mode=TwoWay}"
                              Width="100" />
                  </StackPanel>
                </DataTemplate>
              </DataGridTemplateColumn.CellEditingTemplate>
    
            </DataGridTemplateColumn>
          </DataGrid.Columns>
    
        </DataGrid>
      </Grid>
    </Window>
    


    using System.Collections.ObjectModel;
    using System.Windows;
    
    namespace WpfStackOverflowSpielWiese
    {
      /// <summary>
      /// Interaction logic for Window2.xaml
      /// </summary>
      public partial class Window2 : Window
      {
        public static readonly DependencyProperty ViewModelProperty =
          DependencyProperty.Register("ViewModel", typeof(ViewModelClass), typeof(Window2), new PropertyMetadata(default(ViewModelClass)));
    
        public ViewModelClass ViewModel {
          get { return (ViewModelClass)this.GetValue(ViewModelProperty); }
          set { this.SetValue(ViewModelProperty, value); }
        }
    
        public Window2() {
          this.InitializeComponent();
          this.grid.Items.Clear();
          this.ViewModel = new ViewModelClass();
        }
      }
    
      public class StateClass : DependencyObject
      {
        public static readonly DependencyProperty StateKeyProperty =
          DependencyProperty.Register("StateKey", typeof(string), typeof(ViewModelClass), new PropertyMetadata(default(string)));
    
        public string StateKey {
          get { return (string)this.GetValue(StateKeyProperty); }
          set { this.SetValue(StateKeyProperty, value); }
        }
    
        public static readonly DependencyProperty StateProperty =
          DependencyProperty.Register("State", typeof(string), typeof(StateClass), new PropertyMetadata(default(string)));
    
        public string State {
          get { return (string)this.GetValue(StateProperty); }
          set { this.SetValue(StateProperty, value); }
        }
      }
    
      public class ViewModelClass : DependencyObject
      {
        public static readonly DependencyProperty StateListProperty =
          DependencyProperty.Register("StateList", typeof(ObservableCollection<string>), typeof(ViewModelClass), new PropertyMetadata(default(ObservableCollection<string>)));
    
        public static readonly DependencyProperty AddressCollectionViewSourceProperty =
          DependencyProperty.Register("AddressCollectionViewSource", typeof(ObservableCollection<StateClass>), typeof(ViewModelClass), new PropertyMetadata(default(ObservableCollection<StateClass>)));
    
        public ObservableCollection<StateClass> AddressCollectionViewSource {
          get { return (ObservableCollection<StateClass>)this.GetValue(AddressCollectionViewSourceProperty); }
          set { this.SetValue(AddressCollectionViewSourceProperty, value); }
        }
    
        public ObservableCollection<string> StateList {
          get { return (ObservableCollection<string>)this.GetValue(StateListProperty); }
          set { this.SetValue(StateListProperty, value); }
        }
    
        public ViewModelClass() {
          this.StateList = new ObservableCollection<string>(new[] {"one", "two"});
          this.AddressCollectionViewSource = new ObservableCollection<StateClass>(new[] {new StateClass {State = "state", StateKey = "one"}});
        }
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2016-11-30
      • 1970-01-01
      • 2013-07-14
      • 2010-11-07
      • 1970-01-01
      • 1970-01-01
      • 2016-01-20
      • 2018-09-06
      • 2013-07-11
      相关资源
      最近更新 更多