2015-04-27 121 views
0

嗨新的WPF程序员在这里。我似乎无法得到这个工作,我希望也许你有一些想法。当我在用户定义表(ListBox)中选择一个项目时,我希望它将数据(ObservableCollection)填充到我的数据网格中。然后我将使用下面的插入编辑保存按钮进行编辑。用户定义表(ListBox)中的每个项目都有多个选项和说明。将ListBox选定项目数据绑定到DataGrid的最佳方法WPF

我有一个XAML看起来像这样:

<Grid HorizontalAlignment="Left" Height="505" VerticalAlignment="Top" Width="805"> 
    <Grid.ColumnDefinitions> 
     <ColumnDefinition Width="210*"/> 
     <ColumnDefinition Width="233*"/> 
     <ColumnDefinition Width="315*"/> 
     <ColumnDefinition Width="47*"/> 
    </Grid.ColumnDefinitions> 
    <Grid.RowDefinitions> 
     <RowDefinition Height="33*"/> 
     <RowDefinition Height="217*"/> 
     <RowDefinition Height="86*"/> 
     <RowDefinition Height="89*"/> 
     <RowDefinition Height="81*"/> 
    </Grid.RowDefinitions> 

    <ListBox x:Name="_listbox" HorizontalAlignment="Left" Height="103" VerticalAlignment="Top" Width="210" Margin="0,1,0,0" Grid.Row="1"> 
     <ListBox.ItemContainerStyle> 
      <Style TargetType="{x:Type ListBoxItem}"> 
       <Setter Property="IsSelected" Value="{Binding Selected}"/> 
      </Style> 
     </ListBox.ItemContainerStyle> 

     <ListBoxItem Content="ARNotes" /> 
     <ListBoxItem Content="Item2"/> 
     <ListBoxItem Content="Item3"/> 
     <ListBoxItem Content="Item4"/> 
     <ListBoxItem Content="Item5"/> 
     <ListBoxItem Content="Item6"/> 
    </ListBox> 

    <ComboBox HorizontalAlignment="Left" Height="30" Margin="4,0,0,0" VerticalAlignment="Top" Width="257" Grid.Column="2"> 
     <ComboBoxItem Content="FromCompanyTable"/> 
    </ComboBox> 

    <DataGrid x:Name="_grid" ItemsSource="{Binding SelectedItem, ElementName=_listbox}" AutoGenerateColumns="False" Grid.ColumnSpan="2" Grid.Column="1" Margin="24,2,0,3" Grid.Row="1" > 
     <DataGrid.Columns> 
      <DataGridTextColumn x:Name="Choice" Width="*" Header="Choice" Binding="{Binding choice}"/> 
      <DataGridTextColumn x:Name="Descip" Width="*" Header="Description" Binding="{Binding description}"/> 
     </DataGrid.Columns> 
    </DataGrid> 

而且我的模型:

public class NoteList : ObservableCollection<ARNotes> 
{  
    public NoteList() : base() 
    { 
     Add(new ARNotes("A", "Adjustment")); 
     Add(new ARNotes("C", "Changed")); 
     Add(new ARNotes("D", "Notes")); 
     Add(new ARNotes("G", "Information")); 
    } 
} 

public class ARNotes 
{ 
    private string choice; 
    private string description; 

    public ARNotes(string choice, string description) 
    { 
     this.choice = choice; 
     this.description = description; 
    } 

    public string Choice 
    { 
     get { return choice; } 
     set { choice = value; } 
    } 

    public string Description 
    { 
     get { return description; } 
     set { description = value; } 
    } 
} 
+0

您的'_listbox'没有对象项,因为您为每个项目设置了字面上的“内容”。 – dytori

回答

0

的ItemsSource必须是项目的集合。您将它设置为单个项目。通过使用列表框你没有获得任何东西。我建议仅使用DataGrid并将该ItemsSource绑定到您的NoteList