我正在开发一个新的Wpf项目,并且正在努力将DataGrid中的TextBox绑定到Wpf中的对象列表。 任何人都可以帮我修理吗?
这是我的代码(简化版),通过绑定我的 Orders 对象来生成Datagrid行。 用户可以更改订单项,它应该绑定到下划线对象。 用户点击阅读订单按钮后,我会在文本块中显示更改。问题:TextBox中的更改未更新到Orders对象中。
ObservableCollection<StxOrdr> Orders = new ObservableCollection<StxOrdr>();
private void Window_Initialized(object sender, EventArgs e)
{
Orders.Add(new StxOrdr() { ID = 1, Desc = "Order-#1", Item1 = "11", Item2 = "12", Item3 = "13" });
Orders.Add(new StxOrdr() { ID = 2, Desc = "Order-#2", Item1 = "21", Item2 = "22", Item3 = "23" });
Orders.Add(new StxOrdr() { ID = 3, Desc = "Order-#3", Item1 = "31", Item2 = "32", Item3 = "33" });
Dg2.ItemsSource = Orders;
}
private void ReadUpdatedOrders(object sender, RoutedEventArgs e)
{
TxtBlk.Text = "";
foreach (StxOrdr odr in Orders)
{
TxtBlk.Text += string.Format("{0}: {1} - {2} - {3}\n", odr.Desc, odr.Item1, odr.Item2, odr.Item3);
}
}
Window Xml
<DataGrid x:Name="Dg2" HorizontalAlignment="Left" Margin="21,295,0,0" VerticalAlignment="Top" Height="230" Width="451"
AutoGenerateColumns="false" ItemsSource="{Binding Source=Orders}" >
<DataGrid.Columns>
<DataGridTextColumn Header="ID" Binding="{Binding ID}" />
<DataGridTextColumn Header="Desc" Binding="{Binding Desc}" Width="80"/>
<DataGridTextColumn Header="Item 1" Binding="{Binding Item1}" Width="60"/>
<DataGridTextColumn Header="Item 2" Binding="{Binding Item2}" Width="60"/>
<DataGridTemplateColumn Header="Item 3" >
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBox Text="{Binding Item3, Mode=OneWayToSource}" Width="60" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
<TextBlock x:Name="TxtBlk" HorizontalAlignment="Left" Margin="489,295,0,0" TextWrapping="Wrap" Text=" Updated order details:"
VerticalAlignment="Top" Height="176" Width="408" Background="#FFFFFCBC"/>
<Button x:Name="Btn2_Copy" Content="Read Orders" HorizontalAlignment="Left" Margin="489,476,0,0"
VerticalAlignment="Top" Width="94" Click="ReadUpdatedOrders"/>
用户界面窗口的屏幕截图
答案 0 :(得分:1)
我认为大多数事情都是正确的。确保Orders.cs实现了INotifyPropertyChanged和这行代码
<TextBox Text="{Binding Item3, Mode=OneWayToSource}" Width="60" />
更新为Mode = TwoWay和UpdateSourceTrigger = PropertyChanged。我会改为
<TextBox Text="{Binding Item3, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Width="60" />