Bon*_*ici 2 c# data-binding wpf
我是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;
}
Run Code Online (Sandbox Code Playgroud)
我的数据绑定尝试(在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>
Run Code Online (Sandbox Code Playgroud)
但是当我尝试运行此代码时,成分列表框始终为空.谁能告诉我我做错了什么?
问题是因为您声明和初始化Ingredients列表的方式,将其设为ObservableCollection并仅在构造函数中初始化Ingredients集合,如下所示
public class RecipeDetails
{
public RecipeDetails()
{
_ingredients = new ObservableCollection<RecipeIngredient>();
}
public string Name { get; set; }
public string Description { get; set; }
private ObservableCollection<RecipeIngredient> _ingredients;
private ObservableCollection<RecipeIngredient> Ingredients
{
get { return _ingredients; }
}
}
Run Code Online (Sandbox Code Playgroud)
还有一点要添加到您的方法中,建议在此类上使用INotifyPropertyChanged,以便在TextBox中键入内容时可以轻松实现TwoWay绑定.
| 归档时间: |
|
| 查看次数: |
3174 次 |
| 最近记录: |