2014-10-04 54 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;