使用XAML中的DataContext将简单数据绑定到代码不起作用?

时间:2017-04-12 12:19:40

标签: c# wpf

我正在学习WPF,我想将数据从一些文本框传递到代码:

<Grid Margin="0,0,10,43" Name="dataFrm">
   <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="*"/>
        <RowDefinition Height="*"/>
        <RowDefinition Height="*"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <Label Grid.Column="0">Name</Label>
    <Label Grid.Column="0" Grid.Row="1">Code</Label>
    <Label Grid.Column="0" Grid.Row="2">Categry Id</Label>
    <TextBox Grid.Row="0" Grid.Column="1" x:Name="txtName" Text="{Binding Path=Name, UpdateSourceTrigger=LostFocus}" Width="162" Margin="0,0,0,10" HorizontalAlignment="Left"></TextBox>
    <TextBox Grid.Row="1" Grid.Column="1" x:Name="txtCode" Text="{Binding Path=Code, UpdateSourceTrigger=LostFocus}" Width="162" Margin="0,0,0,10" HorizontalAlignment="Left"></TextBox>
    <TextBox Grid.Row="2" Grid.Column="1" x:Name="txtCatId" Text="{Binding Path=CategoryId, UpdateSourceTrigger=LostFocus}" Width="162" Margin="0,0,0,10" HorizontalAlignment="Left"/>
    <Button  Grid.Row="3" Grid.Column="1" x:Name="btnSave" Click="btnSave_Click" Width="142" Content="Save"/>
</Grid>

当我点击“保存”时,我想将检索到的数据转换为预定义的类:

private void btnSave_Click(object sender, RoutedEventArgs e)
{
    var productVm = (ClsProducts)dataFrm.DataContext;
    MessageBox.Show(productVm.Name);
}

ClsProducts:

public class ClsProducts
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Code { get; set; }
    public int CategoryId { get; set; }
}

DataContext的{​​{1}}为dataFrm

1 个答案:

答案 0 :(得分:1)

确保设置DataContext或其父窗口的Grid属性:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new ClsProducts();
    }
}