开发者

WPF bind DataContext in xaml to ViewModel in code

I have this simplified version of my app in 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>

In C# I have this:

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

In MyItem.cs I do this:

namespace MyApp.Vi开发者_运维问答ew
{
    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;
        }
    }
}

When you end up having too many controls, this can become difficult to maintain. So, how can I tell XAML to do something like:

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


you could just give each control a unique name

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

then in your code , you could just change the data context

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜