DataGrid绑定无法正常工作

时间:2018-05-02 07:43:37

标签: c# wpf mvvm data-binding wpfdatagrid

我对WPF比较陌生。我想允许用户在文本框中输入一些值。当用户按下 Enter 键时,在文本框中输入的值将很快反映在数据网格的“新产品名称”中。我错过了什么吗?

<TextBox x:Name="tbProductName" Text="{Binding NewProductName, UpdateSourceTrigger=Explicit,}" KeyUp="tbProductName_KeyUp"></TextBox>

<DataGrid ItemsSource="{Binding Path=ProductDetails}" >
     <DataGrid.Columns>
        <DataGridTextColumn Header="Old Product Name" Binding="{Binding ProductName}"></DataGridTextColumn>
        <DataGridTextColumn Header="New Product Name">
            <DataGridTextColumn.ElementStyle>
                <Style TargetType="{x:Type TextBlock}">
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding IsSelected}" Value="True">
                            <Setter Property="Text" Value="{Binding NewProductName}"></Setter>
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </DataGridTextColumn.ElementStyle>
        </DataGridTextColumn>
    </DataGrid.Columns>
 </DataGrid> 

XAML代码背后:

private void tbProductName_KeyUp(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Enter)
    {
        TextBox textBox = sender as TextBox;
        textBox.GetBindingExpression(TextBox.TextProperty).UpdateSource();
    }
}

0 个答案:

没有答案