WPF DataContext源代码

时间:2013-11-15 13:42:07

标签: c# wpf data-binding

我通过将控件绑定到类来填充我的控件,如下例所示:

HttpResponseMessage response = await client.GetAsync("/api/Customer/" + txtNumber.Text);
response.EnsureSuccessStatusCode();

var customer = await response.Content.ReadAsAsync<Customer>();
this.DataContext = customer;

这很好用。

我也使用与搜索条件相同的控件,即。应收集用户在任何控件中输入的数据并将其发送回服务器以查询数据库。

是否有一种简单的方法来收集这些数据,或者我是否必须循环控制并自行完成收集?

这是XAML:

<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:Model="clr-namespace:Server.DTO;assembly=Server.DTO" mc:Ignorable="d" x:Class="Client.Forms.Reference.DataForm"
    Title="Preisstufe" Height="346" Width="459" WindowStartupLocation="CenterOwner" ShowInTaskbar="False" ScrollViewer.VerticalScrollBarVisibility="Disabled" ResizeMode="NoResize" Loaded="Window_Loaded">
    <DockPanel LastChildFill="True">
        <StatusBar x:Name="statusBar" DockPanel.Dock="Bottom" Height="20">
            <StatusBarItem x:Name="statusBarItem" Content="" Height="20" VerticalAlignment="Top"/>
        </StatusBar>
    <Grid>
        <Grid.Background>
            <SolidColorBrush Color="{DynamicResource {x:Static SystemColors.ControlLightColorKey}}"/>
        </Grid.Background>
        <Canvas>
            <Label Content="Number:" HorizontalAlignment="Left" Margin="87,33,0,0" VerticalAlignment="Top"/>
            <TextBox x:Name="txtNumber" HorizontalAlignment="Left" Height="24" Margin="185,36,0,211" Text="{Binding Number, Mode=TwoWay, NotifyOnValidationError=true, ValidatesOnExceptions=true}" VerticalAlignment="Center" Width="76" KeyDown="txtNumber_KeyDown"/>

            <Label Content="Description:" HorizontalAlignment="Left" VerticalAlignment="Top" Canvas.Left="87" Canvas.Top="62"/>
            <TextBox x:Name="txtDescription" HorizontalAlignment="Left" Height="24" Margin="185,64,0,183" Text="{Binding Description, Mode=TwoWay, NotifyOnValidationError=true, ValidatesOnExceptions=true}" VerticalAlignment="Center" Width="236"/>

            <Label Content="Abbr:" HorizontalAlignment="Left" VerticalAlignment="Top" Canvas.Left="87" Canvas.Top="91"/>
            <TextBox x:Name="txtAbbr" HorizontalAlignment="Left" Height="24" Margin="185,93,0,154" Text="{Binding Abbr, Mode=TwoWay, NotifyOnValidationError=true, ValidatesOnExceptions=true}" VerticalAlignment="Center" Width="75"/>

            </Canvas>
        </Grid>
    </DockPanel>
</Window>

1 个答案:

答案 0 :(得分:0)

您应该考虑将控件绑定到代码隐藏中的属性。这也适用于TwoWay绑定,可以使您的任务更简单。这是使用DependancyProperties

在WPF中实现的