2015-01-17 3 views

답변

7

d : DataContext와 함께 사용해야하는 인스턴스는 XAML에서 예를 들어 StaticResource으로 선언해야합니다. 나는 데이터 컨텍스트로 사용하는 클래스가 정의

<UserControl x:Class="WpfApplication1.UserControl1" 
      xmlns:local="clr-namespace:WpfApplication1" 
      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:d="http://schemas.microsoft.com/expression/blend/2008" 
      mc:Ignorable="d" 
      d:DesignHeight="300" d:DesignWidth="300"> 
    <UserControl.Resources> 
     <local:MyViewModel x:Key="mockViewModel"/> 
    </UserControl.Resources> 
    <Grid> 
     <ItemsControl d:DataContext="{StaticResource mockViewModel}" 
         ItemsSource="{Binding Items}"> 
      <ItemsControl.ItemTemplate> 
       <DataTemplate> 
        <TextBlock Text="{Binding Name}"/> 
       </DataTemplate> 
      </ItemsControl.ItemTemplate> 
     </ItemsControl> 
    </Grid> 
</UserControl> 

을 다음과 같이 : 여기

당신이 그것을 할 수있는 방법입니다 물론

namespace WpfApplication1 
{ 
    public class Item 
    { 
     public Item(string name) 
     { 
      Name = name; 
     } 

     public string Name { get; private set; } 
    } 

    public class MyViewModel 
    { 
     public List<Item> Items 
     { 
      get 
      { 
       return new List<Item>() { new Item("Thing 1"), new Item("Thing 2") }; 
      } 
     } 
    } 
} 

을, 당신은 또한의 데이터 컨텍스트를 설정할 수 있습니다 UserControl 또는 귀하의 창에 기재하십시오.

다음은 결과입니다 : enter image description here

+3

내가 자원으로로드하는 응용 프로그램도 실행시에로드 할 것이라는 점을 읽었다. 'd : DataContext = "{d : DesignInstance Type = mocks : MyViewModelMock, IsDesignTimeCreatable = True}"를 사용하고 있습니다. –

+1

@ChristopherFrancisco d : DesignInstance도 사용합니다. 디자이너가 때로는 업데이트하는 데 약간의 게으름입니다. – helb

+0

감사합니다. –