2
我是新來WPF和數據綁定,所以希望我可以解釋我有足夠的細節得到一些幫助的問題。數據綁定到數據綁定對象內的列表
我有一個數據綁定到窗口的對象列表。假設它是一份食譜列表。我設法讓應用程序在列表框中顯示每個配方的一些細節,以及在各種文本框中選擇的配方的更多細節。我的問題是,我在每個配方中都有一個配料列表,當我選擇配方時,我想在另一個列表框中顯示配料列表,但我無法弄清楚如何讓數據綁定工作。
我的數據類看起來像:
public class Recipes : ObservableCollection<RecipeDetails>
{
}
public class RecipeDetails
{
public string Name { get; set; }
public string Description { get; set; }
public List<RecipeIngredient> Ingredients;
}
public class RecipeIngredient
{
public string IngredientName { get; set; }
}
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
m_recipes = new Recipes();
// m_recipes initialisation
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
DataContext = m_recipes;
}
private Recipes m_recipes;
}
我的數據綁定嘗試(在XAML)看起來像:
<Window x:Class="RecipeWindow.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Recipe Window" Height="402.687" Width="532.674" Loaded="Window_Loaded">
<Grid>
<ListBox Margin="12,58.176,0,16.362" Name="recipeListBox" Width="209.07" IsSynchronizedWithCurrentItem="True" ItemsSource="{Binding}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}" FontSize="14" Padding="5" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<StackPanel Margin="245.43,58.176,12,47.268" Name="detailsPanel">
<TextBox Text="{Binding Name,UpdateSourceTrigger=PropertyChanged}" Width="140" />
<TextBox Text="{Binding Description,UpdateSourceTrigger=PropertyChanged}" Width="140" />
<ListBox Name="ingredientListBox" Width="209.07" ItemsSource="{Binding Ingredients}" Height="118.17">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding IngredientName}" Padding="5" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</StackPanel>
</Grid>
</Window>
但是當我嘗試運行這段代碼,成分表盒子總是空的。誰能告訴我我做錯了什麼?
工作就像一個魅力,除非我不需要在構造函數中初始化它。使其成爲一個公共財產,如: public ObservableCollection成分 {get;組; } 似乎工作正常。 –
Bonnici
2008-12-07 08:49:45