我仍然是wpf-mvvm的初学者。我有一个与集合绑定的数据网格。我希望文本框中写的文本填充我的数据网格的第一列“InvoiceNb”的每一行。
我该怎么做?
<Grid DataContext="{Binding Source={StaticResource invoice}}">
<StackPanel Orientation="Horizontal">
<TextBox Width="71" Name="InvoiveNumber" Text="{Binding DataContext.Collection/suppInvNumber, ElementName=InvoiveNumber, Mode=OneWay}">
<!-- My textbox -->
</TextBox>
<DatePicker>
</DatePicker>
<Label Content="Shop"/>
<ComboBox Margin="5"
ItemsSource="{Binding Collection, Source={StaticResource shop}}"
DisplayMemberPath="shop1" Width="53"
/>
<Label Content="Supplier"/>
<ComboBox Margin="5"
ItemsSource="{Binding Collection, Source={StaticResource supplier}}"
DisplayMemberPath="supplier"
SelectedItem="{Binding Selected, Source={StaticResource supplier}, Mode=TwoWay}" Width="46"/>
</StackPanel>
<DataGrid x:Name="dataGridInvoice" Margin="5" Grid.Row="1"
ItemsSource="{Binding Collection}" AutoGenerateColumns="False">
<DataGrid.Columns>
<!-- My column --> <DataGridTextColumn x:Name="dataGridTextColumn" Header="Supplier Invoice Nb" Binding="{Binding suppInvNumber, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" Width="*"/>
<DataGridComboBoxColumn Header="Ref Supplier"
ItemsSource="{Binding Products, Source={StaticResource supplier}, Mode=TwoWay}"
DisplayMemberPath="refsup"
SelectedValueBinding="{Binding refSupp}"
SelectedValuePath="refsup"
Width="*"/>
<DataGridTextColumn Header="Quantity" Binding="{Binding quantity, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" Width="*"/>
<DataGridTextColumn Header="Prix/MOQ" Binding="{Binding unitPrice, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" Width="*"/>
<DataGridTextColumn Header="Total Price" Binding="{Binding totalPrice, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" Width="*"/>
</DataGrid.Columns>
</DataGrid>
<Button x:Name="BtnAdd" Content="Save" Command="{Binding SaveCommand}" Margin="94,0"/>
</StackPanel>
</Grid>
答案 0 :(得分:1)
您可以将文本直接绑定到DataGrid SelectedItem:
<TextBox Width="71" Name="InvoiveNumber"
Text="{Binding ElementName=dataGridInvoice, Path=SelectedItem.InvoiceNb}"/>
或者在ViewModel中定义CurrentItem属性并将DataGrid SelectedItem绑定到该属性,然后将TextBox的Text绑定到DataContext的CurrentItem。
<TextBox Width="71" Name="InvoiveNumber"
Text="{Binding CurrentItem.InvoiceNb}"/>
<DataGrid SelectedItem={Binding CurrentItem, Mode=TwoWay} .... />