我正在尝试 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>
我有一个带有属性 MenuHeader
和 MenuItems
的 MenuViewModel
。我在运行时获取这两个属性的值。前者绑定(bind)到 TextBlock
的文本,后者绑定(bind)到 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");
}
}
}
提前致谢。
最佳答案
您正在使用 ViewModel 的默认构造函数在 XAML 中创建 ViewModel,该构造函数不执行任何操作。您的所有人口代码都位于从未被调用的非默认构造函数中。
更常见的方法是在代码中创建 ViewModel,然后显式使用 View.DataContext = ViewModel 或隐式使用 DataTemplate 将其注入(inject) View 。
关于c# - 一个简单的 Wpf MVVM 绑定(bind)问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10072430/