Wpf DataGrid ComboBox 列-完整代码

时间:2024-05-02 11:28:23
  public class EnumDesp
  {
     public int Id { get; set; }
     public string Name { get; set; }
  }

public class MainWindowViewModel : BindableBase
{
    private string _title = "Prism Application";
    public string Title
    {
        get { return _title; }
        set { SetProperty(ref _title, value); }

    }

    public ObservableCollection<RealDigitViewModel> Digits { get; set; }=new ObservableCollection<RealDigitViewModel>();
    public ObservableCollection<EnumDesp> DigitTypes { get; set; }

    public MainWindowViewModel()
    {
     
        DigitTypes = DigitTypeConverter.DigitTypes;
        this.Digits.Add(new RealDigitViewModel()
        {
            Name = "Abc",
            DigitType = 1
        });

        this.Digits.Add(new RealDigitViewModel()
        {
            Name = "Def",
            DigitType = 2
        });
    }

 
}
<Window x:Class="BlankApp1.Views.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:prism="http://prismlibrary.com/"
        prism:ViewModelLocator.AutoWireViewModel="True"
        Title="{Binding Title}" Height="350" Width="525" >
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"></RowDefinition>
            <RowDefinition></RowDefinition>
        </Grid.RowDefinitions>
        <Button Grid.Row="0" Command="{Binding MyCommand}" Content="Me" ></Button>
       <DataGrid Grid.Row="1" ItemsSource="{Binding Digits}" AutoGenerateColumns="False">
            <DataGrid.Columns>
                <DataGridTextColumn Header="Name" Binding="{Binding Name}"/>
            
                <DataGridTemplateColumn Header="Digit" Width="100">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <ComboBox 
                                ItemsSource="{Binding DataContext.DigitTypes, RelativeSource={RelativeSource AncestorType={x:Type Window}}}"
                              SelectedValue="{Binding DigitType,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
                           
                              SelectedValuePath="Id"
                              DisplayMemberPath="Name"/>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>

            </DataGrid.Columns>
        </DataGrid>
    </Grid>
</Window>