WPF绑定Model的实例对象

时间:2023-12-18 09:41:50

创建一个用户控件

1. behindcode指定this.DataContext=XXViewModel

2. "{Binding DataContext.EditModel.MId,RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}}"

Xaml代码如下:

<Grid Name="eg" Grid.Row="4" Grid.ColumnSpan="8"  Visibility="{Binding DataContext.EditVisible,RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}}">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*"></ColumnDefinition>
                <ColumnDefinition Width="*"></ColumnDefinition>
                <ColumnDefinition Width="*"></ColumnDefinition>
                <ColumnDefinition Width="*"></ColumnDefinition>
                <ColumnDefinition Width="*"></ColumnDefinition>
                <ColumnDefinition Width="*"></ColumnDefinition>
                <ColumnDefinition Width="*"></ColumnDefinition>
            </Grid.ColumnDefinitions>
            <Grid.RowDefinitions>
                <RowDefinition></RowDefinition>
                <RowDefinition></RowDefinition>
                <RowDefinition></RowDefinition>
                <RowDefinition></RowDefinition>
            </Grid.RowDefinitions>
            <Label Content="年月:" Grid.Column="0" Grid.Row="0" VerticalAlignment="Center"></Label>
            <Label Content="机种:" Grid.Column="2" Grid.Row="0" VerticalAlignment="Center"></Label>
            <Label Content="EMS邮件内容:" Grid.Column="4" Grid.Row="0" VerticalAlignment="Center"></Label>

<DatePicker Background="Blue"  Grid.Row="0" Grid.Column="1" SelectedDate="{Binding DataContext.EditModel.Monthly,RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}}"></DatePicker>
            <ComboBox DisplayMemberPath="Value"  SelectedValuePath="Key" Grid.Row="0" Grid.Column="3"
                      SelectedValue="{Binding DataContext.EditModel.MId,RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}}"  ItemsSource="{Binding DataContext.MachineList,RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}}"/>