我正在嘗試使用WPF MVVM。我在XAML簡單的WPF MVVM綁定問題
<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是空的。
編輯:視圖模型準則
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'? – ChrisF 2012-04-09 11:23:19
發佈ViewModel的代碼 – 2012-04-09 11:23:45
您是否將視圖的數據上下文設置爲必需的視圖模型? – 2012-04-09 11:29:14