我是WPF的新手,我已经找到一些指向正确方向的帖子,但我似乎错过了一些东西。
我的应用程序有一个由tabpages组成的主窗口。每个标签页都包含一个对象树,旁边应显示所选对象。
我使用MVVM模式(根据我的理解),遵循Demo 2
目前,我的ProductTab的XAML如下所示:
<UserControl x:Class="ProductPrototype.View.ProductTab"
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:views="clr-namespace:ProductPrototype.View"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="200px" />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<TreeView ItemsSource="{Binding Products}" Grid.Column="0">
<TreeView.ItemContainerStyle>
<!-- This Style binds a TreeViewItem to a PersonViewModel. -->
<Style TargetType="{x:Type TreeViewItem}">
<Setter Property="IsExpanded" Value="{Binding IsExpanded, Mode=TwoWay}" />
<Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}" />
<Setter Property="FontWeight" Value="Normal" />
<Style.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="FontWeight" Value="Bold" />
</Trigger>
</Style.Triggers>
</Style>
</TreeView.ItemContainerStyle>
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Children}">
<TextBlock Text="{Binding Name, StringFormat= '\{0\} (Product)'}" />
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
<!--<views:ProductDescription Grid.Column="1"/>-->
<ListBox Grid.Column="1" ItemsSource="{Binding SelectedProduct}">
<TextBox Text="{Binding Name}" Width="100px"/>
</ListBox>
</Grid>
cs文件只是将一个ProductTreeViewModel分配给DataContext。
我的ProductTreeviewModel看起来像这样(我不得不向SelectedProduct添加一个setter,因为否则我无法绑定它,我的第三个链接的解决方案使用它而没有设置):
namespace ProductPrototype.ViewModel
{
public class ProductTreeViewModel : TreeViewItemViewModel
{
public ProductViewModel SelectedProduct
{
get {
//the first time this is called productViewModel is null
ProductViewModel productViewModel = Products.FirstOrDefault(i => i.IsSelected);
//MessageBox.Show(productViewModel.Name);
return productViewModel;
}
set { MessageBox.Show("Setter is called"); }
}
private ReadOnlyCollection<ProductViewModel> _products = null;
public ReadOnlyCollection<ProductViewModel> Products
{
get { return _products; }
}
public ProductTreeViewModel(Product[] products) : base (null, true)
{
_products = new ReadOnlyCollection<ProductViewModel>(
(from product in products
select new ProductViewModel(product))
.ToList());
}
}
}
有几件事我不确定: