有没有办法同时用静态和动态项填充列表框?
我正在编写一个windows phone 7应用程序,希望在顶部或底部有一个静态listboxItem,然后从viewModel绑定其他项目。我尝试先设置静态listboxItem,然后再设置dataTemplate,但静态项被动态项替换。
编辑:
我发现有几篇文章展示了如何创建一个从允许多个模板的listbox继承的自定义控件。我如何创建一个自定义控件,为静态项添加一个部分,无论绑定如何,这些静态项始终存在。
发布于 2010-06-30 01:32:55
如果您正在尝试执行MVVM,并且还在双向绑定ListBox的SelectedItem,那么只将一个集合绑定到ItemsSource属性将会容易得多。
你能用静态项预先填充ViewModel中的集合吗?然后,当动态项可用时,您可以将它们合并到已经存在的集合中(从web服务或其他任何地方返回)。无论如何,您似乎都希望在ViewModel中使用这种逻辑,并且只向视图公开一个列表,以便与ListBox一起使用。
发布于 2010-07-03 03:52:35
因为有两种不同类型的项,所以我认为最好的方法是创建一个定制的ListBox子类,让添加一个新的DependencyProperty,以允许您绑定和显示第二个列表。这还需要一种新的默认样式,以便在与普通<ItemsPresenter/>
相同的ScrollViewer中适当地显示第二个列表。
下面是我的自定义ListBox的一个示例,以实现这一点:
public class MyListBox : ListBox
{
public MyListBox()
: base()
{
this.DefaultStyleKey = typeof(MyListBox);
}
public static readonly DependencyProperty StaticItemsProperty = DependencyProperty.Register(
"StaticItems",
typeof(IList),
typeof(MyListBox),
null);
public IList StaticItems
{
get { return (IList)GetValue(StaticItemsProperty); }
set { SetValue(StaticItemsProperty, value); }
}
}
然后,您必须将整个默认ListBox样式复制到您的主题/Generic.xaml资源字典中,并将其修改为MyListBox控件的默认样式。我唯一修改的默认样式(除了TargetType属性)是ScrollViewer的内容,其中包含原始列表:
<Style TargetType="custom:MyListBox">
<!-- all the same old XAML for the normal ListBox -->
<ScrollViewer x:Name="ScrollViewer" Background="{TemplateBinding Background}" BorderBrush="Transparent" BorderThickness="0" Padding="{TemplateBinding Padding}" TabNavigation="{TemplateBinding TabNavigation}">
<StackPanel Orientation="Vertical">
<ItemsControl ItemsSource="{TemplateBinding StaticItems}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBox Text="{Binding}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<ItemsPresenter/>
</StackPanel>
</ScrollViewer>
<!-- rest of the same old ListBox XAML -->
</Style>
正如您所看到的,我修改了ScrollViewer,它通常只包含ListBox的ItemsPresenter,并将其替换为一个StackPanel,其中包含一个绑定到我添加到MyListBox的新StaticItems DependencyProperty的新ItemsControl。我修改了此ItemsControl的DataTemplate以显示TextBox。然后,具有普通ItemsPresenter的普通ItemsTemplate将显示在ScrollViewer中静态列表的下方。
然后,可以使用这个自定义ListBox代替普通的ListBox来绑定到ViewModel中的两个不同列表,既绑定到静态项,也绑定到动态项。
<custom:MyListBox x:Name="ListBox" ItemsSource="{Binding DynamicItems}" StaticItems="{Binding StaticItems}"/>
https://stackoverflow.com/questions/3143032
复制相似问题