2015-01-17 19 views

Trả lời

7

Ví dụ bạn phải sử dụng với d: DataContext phải được khai báo trong XAML, ví dụ: StaticResource.

Đây là cách bạn có thể làm điều đó:

<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> 

Lớp tôi sử dụng như bối cảnh dữ liệu được quy định như sau:

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") }; 
      } 
     } 
    } 
} 

Tất nhiên, bạn cũng có thể đặt bối cảnh dữ liệu trên UserControl hoặc trên Cửa sổ của bạn.

Dưới đây là kết quả: enter image description here

+3

Tôi đọc mà tải nó như là một nguồn tài nguyên sẽ làm cho các ứng dụng cũng tải nó về thời gian chạy. Tôi đang sử dụng 'd: DataContext =" {d: DesignInstance Type = mocks: MyViewModelMock, IsDesignTimeCreatable = True} 'nhưng nó không hoạt động –

+1

@ChristopherFrancisco Sử dụng d: DesignInstance hoạt động quá. Hãy thử khởi động lại VS và xây dựng lại giải pháp của bạn Nhà thiết kế đôi khi hơi lười biếng khi cập nhật ... – helb

+0

nó hoạt động, cảm ơn bạn –

Các vấn đề liên quan