【发布时间】:2012-04-09 11:18:58
【问题描述】:
我正在尝试 WPF MVVM。我在 XAML 中编写了以下代码
<UserControl x:Class="Accounting.Menu"
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"
xmlns:local="clr-namespace:Accounting"
mc:Ignorable="d"
d:DesignHeight="105" d:DesignWidth="300">
<UserControl.DataContext>
<local:MenuViewModel/>
</UserControl.DataContext>
<StackPanel>
<StackPanel>
<TextBlock Text="{Binding Path=MenuHeader}"/>
</StackPanel>
<ListBox ItemsSource="{Binding Path=MenuItems}" Height="70"/>
</StackPanel>
</UserControl>
我有一个MenuViewModel 属性MenuHeader 和MenuItems。我在运行时获得了这两个属性的值。前者绑定到TextBlock 的文本,后者绑定到ListBox 的ItemSource。但是当我运行解决方案时,TextBlock 和 ListBox 是空的。
编辑:ViewModel 代码
public class MenuViewModel: ViewModelBase
{
AccountingDataClassesDataContext db;
private string _menuType;
public string MenuHeader { get; set; }
public ObservableCollection<string> MenuItems { get; set; }
public MenuViewModel()
{
}
public MenuViewModel(string menuType)
{
this._menuType = menuType;
db = new AccountingDataClassesDataContext();
if (menuType == "Vouchers")
{
var items = db.Vouchers.OrderBy(t => t.VoucherName).Select(v => v.VoucherName).ToList<string>();
if (items.Any())
{
MenuItems = new ObservableCollection<string>(items);
MenuHeader = "Vouchers";
}
}
else
{
System.Windows.MessageBox.Show("Menu not found");
}
}
}
提前致谢。
【问题讨论】:
-
您是否在视图模型上实现了
INotifyPropertyChanged? -
贴出你的 ViewModel 的代码
-
您是否将视图的数据上下文设置为所需的视图模型?
-
@DarrenYoung:是的,菜单(视图)需要 datacontext MenuViewModel
-
@ChrisF:INotifyPropertyChanged 不是问题。它与祖先绑定或相对绑定有关吗?