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"/>
嗨, 我试过了,它似乎没有工作。 XAML中的DataContext =“prop1”如何与除名称外的C#中的mycontrol1.DataContext = vm1相关? 为什么在XAML中设置“prop1”名称,而在C#中设置它为vm1? – immuner 2009-10-26 06:57:03
@vark,我只是跟随你的榜样。 vm1和vm2表示不同的数据上下文。 – 2009-10-26 07:39:21
嘿安德鲁,是的,我明白这一点。但是我无法完成这项工作。我已经建立了一个小样本项目,说明这两种方法:http://www.2shared.com/file/8688933/866fc885/usercustom.html。有什么我错过了你的解释吗? – immuner 2009-10-26 11:46:41