WPF将xaml中的DataContext绑定到代码中的ViewModel

时间:2009-10-24 07:25:11

标签: c# wpf xaml data-binding datacontext

我在XAML中有我的应用程序的简化版本:

<UserControl
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
      xmlns:uc="clr-namespace:myApp.MyControls"    
      x:Class="myApp.View.MyItem"
      x:Name="testWind"
      Width="Auto" Height="Auto" Background="White">
    <Grid x:Name="LayoutRoot">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <GroupBox x:Name="GroupBox" Header="G" Grid.Row="0">
            <WrapPanel>
                <GroupBox x:Name="GroupBox11">
                    <StackPanel Orientation="Vertical">
                        <uc:customControl1 Margin="0,4,0,0" 
                                           property1="{Binding prop1.property1}" 
                                           property2="{Binding prop1.property2}"
                                           property3="{Binding prop1.property3}"/>
                        <uc:customControl2 Margin="0,4,0,0" 
                                           property1="{Binding prop2.property1}" 
                                           property2="{Binding prop2.property2}"
                                           property3="{Binding prop2.property3}"/>
                    </StackPanel>
                </GroupBox>
            </WrapPanel>
        </GroupBox>
    </Grid>
</UserControl>

在C#中我有这个:

namespace MyApp.ViewModel
{
    public class MyItemViewModel
    {
        public object prop1 { get; set; }
        public object prop2 { get; set; }
    }
}

在MyItem.cs中我这样做:

namespace MyApp.View
{
    public partial class MyItem : UserControl
    {
        public MyItem()
        {
             this.InitializeComponent();
             MyItemViewModel vm = new MyItemViewModel();
             vm.prop1 = new blah blah(); // setting properties
             vm.prop2 = new blah blah(); // setting properties
             this.DataContext = vm;
        }
    }
}

当您最终拥有太多控件时,这可能会变得难以维护。那么,我怎么能告诉XAML做类似的事情:

    <uc:customControl1 Margin="0,4,0,0" DataContext="prop1"/>
    <uc:customControl2 Margin="0,4,0,0" DataContext="prop2"/>

1 个答案:

答案 0 :(得分:1)

你可以给每个控件一个唯一的名字

<uc:customControl1 x:Name="mycontrol1" Margin="0,4,0,0" DataContext="prop1"/>
<uc:customControl2 x:Name="mycontrol2" Margin="0,4,0,0" DataContext="prop2"/>

然后在您的代码中,您可以只更改数据上下文

   mycontrol1.DataContext = vm1;
   mycontrol2.DataContext = vm2;