2009-10-24 81 views
1

我有我的應用程序的XAML這個簡化版本:WPF綁定的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

你可以給你的代碼中的每個控制的唯一名稱

<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; 
+0

嗨, 我試過了,它似乎沒有工作。 XAML中的DataContext =「prop1」如何與除名稱外的C#中的mycontrol1.DataContext = vm1相關? 爲什麼在XAML中設置「prop1」名稱,而在C#中設置它爲vm1? – immuner 2009-10-26 06:57:03

+0

@vark,我只是跟隨你的榜樣。 vm1和vm2表示不同的數據上下文。 – 2009-10-26 07:39:21

+0

嘿安德魯,是的,我明白這一點。但是我無法完成這項工作。我已經建立了一個小樣本項目,說明這兩種方法:http://www.2shared.com/file/8688933/866fc885/usercustom.html。有什麼我錯過了你的解釋嗎? – immuner 2009-10-26 11:46:41