简体   繁体   中英

MVVM DataGrid ComboBox SelectedValue Bindfing

i have 2 datagrid and i want on first datagrid to have a combobox with the colection of the second datagrid and whene i select a value from the combobox the value to be put insice the first datagrid.

In my case when i select a materials from combobox i want the CoefD column to be put automaticaly. Here is my code.

And when i save the file and i want to open back the material selectedi want to stay there.

Picture with the program datagrids Click

Model: TName(First datagrid)

public class TMaterial : Changed
    {
        public string name;
        public string color;
        private string materialn;
        private string coefDn;
        private string nameDraw;
        private string drawPath;
        

        public string Name
        {
            get { return name; }
            set
            {
                if (name != value)
                {
                    name = value;
                    RaisePropertyChanged("Name");
                }
            }
        }
        
        public string Color
        {
            get { return color; }
            set
            {
                if(color != value)
                {
                    color = value;
                    RaisePropertyChanged("Color");
                }
            }
        }

        

        public string Materialn
        {
            get { return materialn; }

            set
            {
                if (materialn != value)
                {
                    materialn = value;
                    RaisePropertyChanged("Materialn");
                }
            }
        }

        public string CoefDn
        {
            get { return coefDn; }

            set
            {
                if (coefDn != value)
                {
                    coefDn = value;
                    RaisePropertyChanged("CoefDn");
                }
            }
        }
        public string NameDraw
        {
            get { return nameDraw; }

            set
            {
                if (nameDraw != value)
                {
                    nameDraw = value;
                    RaisePropertyChanged("NameDraw");
                }
            }
        }

        public string DrawPath
        {
            get { return drawPath; }

            set
            {
                if (drawPath != value)
                {
                    drawPath = value;
                    RaisePropertyChanged("DrawPath");
                }
            }
        }


        public override string ToString()
        {
            return name;
        }
}

Model: TMaterial(Second datagrid)

public class TMaterial : Changed
    {
        private string material;
        private string coefD;

        public string Material
        {
            get { return material; }

            set
            {
                if(material != value)
                {
                    material = value;
                    RaisePropertyChanged("Material");
                }
            }
        }

        public string CoefD
        {
            get { return coefD; }

            set
            {
                if(coefD != value)
                {
                    coefD = value;
                    RaisePropertyChanged("CoefD");
                }
            }
        }
    }

ViewModel:

public  class AddNameViewModel : Changed
    {
        private TName tnm;
        
        private ObservableCollection<TName> _dimensionName;
        private ObservableCollection<TMaterial> _materials;
        public AddNameViewModel()
        {
            DimensionName = new ObservableCollection<TName>
            {
                new TName{ Name="All"},
            };

            

            Materials = new ObservableCollection<TMaterial>
            {
                new TMaterial{Material="Aluminium" , CoefD="23.1"},
                new TMaterial{ Material="Brass",CoefD="19"},
                new TMaterial{ Material="Carbon Steel",CoefD="10.8"},
                new TMaterial{ Material="Concrete",CoefD="12"},
                new TMaterial{ Material="Platinum",CoefD="9"},
                new TMaterial{ Material="Iron",CoefD="11.8"},
            };

            
        }
        
        public ObservableCollection<TMaterial> Materials
        {
            get { return _materials; }

            set
            {
                if (_materials != value)
                {
                    _materials = value;
                    RaisePropertyChanged("Materials");
                }
            }
        }

        public ObservableCollection<TName> DimensionName
        {
            get { return _dimensionName; }
            set
            {
                if (_dimensionName != value)
                {
                    _dimensionName = value;
                    RaisePropertyChanged("DimensionName");
                }
            }
        }
        
        private TName sdimensionName;
        private TMaterial smaterials;
        public TName SDimensionName
        {
            get { return sdimensionName; }
            set
            {
                if (sdimensionName != value)
                {
                    sdimensionName = value;
                    RaisePropertyChanged("SDimensionName");
                }
            }
        }

        public TMaterial SMaterials
        {
            get { return smaterials; }

            set
            {
                if (smaterials != value)
                {
                    smaterials = value;
                    RaisePropertyChanged("SMaterials");
                }
            }
        }
        
        
    }

View XAML DG:

<Grid Name="GridC" Margin="0,0,0,-203" >
        <DataGrid CanUserAddRows="True"  CurrentCellChanged="NameDataGrid_CurrentCellChanged" AutoGenerateColumns="False" ItemsSource="{Binding DimensionName,NotifyOnSourceUpdated=True}" RowEditEnding="NameDataGrid_RowEditEnding" Name="NameDataGrid" HorizontalAlignment="Left"  VerticalAlignment="Top" Loaded="NameGrid_Load" Margin="0,25,0,0"  Height="auto" Width="auto" >
            <DataGrid.Columns >
                <DataGridTextColumn  Header="Name" Binding="{Binding Name , Mode=TwoWay}">
                    <DataGridTextColumn.ElementStyle>
                        <Style TargetType="{x:Type TextBlock}">
                            <Setter Property="Background" Value="{Binding Color}"/>
                        </Style>
                    </DataGridTextColumn.ElementStyle>
                </DataGridTextColumn>
                <DataGridTemplateColumn Header="Color">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <xctk:ColorPicker  SelectedColorChanged="ColorPicker_SelectedColorChanged" Background="{Binding Color}" SelectedColor="{Binding Color,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
                
                <DataGridTemplateColumn Header="Material">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <ComboBox SelectionChanged="ComboBox_SelectionChanged"
                            Width="150"
                            IsEditable="True"
                            IsDropDownOpen="False"
                            ItemsSource="{Binding 
                                Path = DataContext.Materials, 
                                RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}"
                            DisplayMemberPath="Material"
                                                                                     
                            SelectedItem="{Binding SMaterials}"
                            IsReadOnly="True"
                             >
                            </ComboBox>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>

                <DataGridTextColumn  IsReadOnly="False" Header="Coef"  Binding="{Binding SMaterials.CoefD,NotifyOnSourceUpdated =True}"/>
                <DataGridTextColumn IsReadOnly="True" Header="Drawing Number" Binding="{Binding NameDraw , Mode=TwoWay}">
                    <DataGridTextColumn.CellStyle>
                        <Style TargetType="DataGridCell">
                            <Setter Property="ToolTip">
                                <Setter.Value>
                                    <Image RenderOptions.BitmapScalingMode="Fant" Width="350" Height="350" Source="{Binding DrawPath}"/>
                                </Setter.Value>
                            </Setter>
                        </Style>
                    </DataGridTextColumn.CellStyle>
                </DataGridTextColumn>

                <DataGridTemplateColumn>

                    <DataGridTemplateColumn.CellTemplate>

                        <DataTemplate>

                            <Button Content="Add Drawing" Click="AddDrawing_Click_1"/>

                        </DataTemplate>

                    </DataGridTemplateColumn.CellTemplate>

                </DataGridTemplateColumn>
                <DataGridTemplateColumn>

                    <DataGridTemplateColumn.CellTemplate>

                        <DataTemplate>

                            <Button x:Name="delet" Click="Delete_Click_1">
                                <StackPanel>
                                    <Image Source="/Image/delete2.jpg" Width="20" Height="20"/>
                                </StackPanel>
                            </Button>

                        </DataTemplate>

                    </DataGridTemplateColumn.CellTemplate>

                </DataGridTemplateColumn>
            </DataGrid.Columns>

        </DataGrid>
</Grid>

First of all, please understand that it is a sample code that I made, not the code you used.
The whole source code is in Github .

Model - Employees (first datagrid)

public class Employees
{
    public string Name { get; set; }
    public int Age { get; set; }
    public Department Department { get; set; }
}

Model - Department (second datagrid)

public class Department
{
    public string DepartmentCode { get; set; }
    public string DepartmentName { get; set; }
}

Take the model you want to bind (Department) as a variable in the Employee class.

ViewModel

public class MainViewModel : ObservableObject
{
    private ObservableCollection<Employees> _employees;
    public ObservableCollection<Employees> Employees
    {
        get { return _employees; }
        set { _employees = value; OnPropertyChanged(); }
    }

    private ObservableCollection<Department> _departments;
    public ObservableCollection<Department> Departments
    {
        get { return _departments; }
        set { _departments = value; OnPropertyChanged(); }
    }

    private string _departmentName;
    public string DepartmentName
    {
        get { return _departmentName; }
        set { _departmentName = value; OnPropertyChanged(); }
    }

    public MainViewModel()
    {
        Employees = GetEmployees();
        Departments = GetDepartments();
    }

    private ObservableCollection<Employees> GetEmployees()
    {
        ObservableCollection<Employees> employees = new ObservableCollection<Employees>
        {
            new Employees { Name = "James", Age = 30 },
            new Employees { Name = "Elena", Age = 26 },
            new Employees { Name = "Rookie", Age = 38 }
        };
        return employees;
    }

    private ObservableCollection<Department> GetDepartments()
    {
        ObservableCollection<Department> departments = new ObservableCollection<Department>
        {
            new Department { DepartmentCode = "0001", DepartmentName = "Develop" },
            new Department { DepartmentCode = "0002", DepartmentName = "Marketing" },
            new Department { DepartmentCode = "0003", DepartmentName = "HR" }
        }; 
        return departments;
    }
}

MainView.xaml

<Grid VerticalAlignment="Top">
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="3*"/>
        <ColumnDefinition Width="2*"/>
    </Grid.ColumnDefinitions>
        
    <DataGrid AutoGenerateColumns="False" SelectionMode="Single" CanUserAddRows="False"
                ItemsSource="{Binding Employees}" Grid.Column="0" AlternatingRowBackground="#F1F1F1" Height="100">
        <DataGrid.Columns>
            <DataGridTextColumn Header="Name" Binding="{Binding Name}" IsReadOnly="True" Width="70"/>
            <DataGridTextColumn Header="Age" Binding="{Binding Age}" IsReadOnly="True" Width="50"/>
            <DataGridComboBoxColumn Header="DepartmentCode" SelectedItemBinding="{Binding Department, UpdateSourceTrigger=PropertyChanged}"
                                    DisplayMemberPath="DepartmentCode" Width="120">
                <DataGridComboBoxColumn.ElementStyle>
                    <Style TargetType="{x:Type ComboBox}">
                        <Setter Property="ItemsSource" Value="{Binding RelativeSource={RelativeSource AncestorType=UserControl},Path=DataContext.Departments}"/>
                    </Style>
                </DataGridComboBoxColumn.ElementStyle>
                <DataGridComboBoxColumn.EditingElementStyle>
                    <Style TargetType="{x:Type ComboBox}">
                        <Setter Property="ItemsSource" Value="{Binding RelativeSource={RelativeSource AncestorType=UserControl},Path=DataContext.Departments}"/>
                    </Style>
                </DataGridComboBoxColumn.EditingElementStyle>
            </DataGridComboBoxColumn>
            <DataGridTextColumn Header="DepartmentName" Binding="{Binding Department.DepartmentName}" IsReadOnly="True" Width="*"/>
        </DataGrid.Columns>
    </DataGrid>

    <DataGrid AutoGenerateColumns="False" SelectionMode="Single" CanUserAddRows="False"
                ItemsSource="{Binding Departments}" Grid.Column="1" Width="250" AlternatingRowBackground="#F1F1F1">
        <DataGrid.Columns>
            <DataGridTextColumn Header="Code" Binding="{Binding DepartmentCode}" IsReadOnly="True" Width="100"/>
            <DataGridTextColumn Header="Name" Binding="{Binding DepartmentName}" IsReadOnly="True" Width="*"/>
        </DataGrid.Columns>
    </DataGrid>
</Grid>

Since the entire Department model is bound to the SelectItem of ComboBox ,
the 'DepartmentName' is automatically bound as the 'DepartmentCode' is selected in ComboBox .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM