2014-10-04 45 views
0

有没有办法将代码的C#部分中创建的数组绑定到ListBox,以便在设计时显示?将数组绑定到列表框,以便在运行时出现

喜欢的东西

XAML

<ListBox ItemsSource="{Binding MyStrings}"> 
    <ListBox.ItemTemplate> 
     <DataTemplate> 
      <TextBox Text={Binding} /> 
     </DataTemplate> 
    </ListBox.ItemTemplate> 
</ListBox> 

C#

public string[] MyStrings = new string[] {"A", "B", "C"}; 

回答

1

运行时的DataContext也将在设计模式下工作。你需要做的就是在单独的ViewModel (这也是MVVM模式推荐的)中提取出代码,并在那里声明数组,并简单地将DataContext绑定到ViewModel。

XAML:

<Window x:Class="WpfApplication1.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:local="clr-namespace:WpfApplication1" 
     Title="MainWindow" Height="350" Width="525"> 
    <Window.DataContext> 
     <local:MainWindowViewModel/> 
    </Window.DataContext> 
    <StackPanel> 
     <ListBox ItemsSource="{Binding MyStrings}"/> 
    </StackPanel> 
</Window> 

视图模型:

public class MainWindowViewModel 
{  
    string[] myStrings = new string[] { "A", "B", "C" }; 
    public string[] MyStrings 
    { 
     get 
     { 
      return myStrings; 
     } 
    } 
} 

设计师:

enter image description here

0

你需要创建一个自定义类型的第一个数据存储为它的属性,像这样:

public class Student 
{ 
    public string Name { get; set; } 
    public int Age { get; set; } 
} 

然后使用类型创建一个列表,像这样:在XMAL

List<Student> list1 = new List<Student>() 
{ 
    new Student() { Name = "Bob", Age = 12 }, 
    new Student() { Name = "John", Age = 30 }, 
}; 

,这样做:

<Grid> 
     <ListBox x:Name="myList" ItemsSource="{Binding}"> 
      <ListBox.ItemTemplate> 
       <DataTemplate> 
        <StackPanel Orientation="Horizontal" Margin="2"> 
         <TextBlock Text="{Binding Name}"/> 
         <TextBlock Text="{Binding Age}"/> 
        </StackPanel> 
       </DataTemplate> 
      </ListBox.ItemTemplate> 
     </ListBox> 

    </Grid> 

最后在运行时,初始myList中的DataContext像这样:

myList.DataContext = list1;