2010-06-01 53 views
0

我有一个用户控件,其中包含一个列表框和几个按钮。用户控件与列表框和父控件(MVVM)之间的绑定

<UserControl x:Class="ItemControls.ListBoxControl" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"> 
    <Grid> 
     <ListBox:ExtendedListBox SelectionMode="Single" ItemsSource="{Binding LBItems}" Height="184"> 
       <ListBox.ItemTemplate> 
        <DataTemplate> 
         <CheckBox Content="{Binding}"/> 
        </DataTemplate> 
       </ListBox.ItemTemplate> 
     </ListBox> 
<Button Command="RemoveCommand"/> 
</Grid> 
</UserControl> 

而后面的代码:

public static readonly DependencyProperty RemoveCommandProperty = 
DependencyProperty.Register("RemoveCommand", typeof(ICommand), typeof(ListBoxControl), null); 

public ICommand RemoveCommand 
{ 
    get { return (ICommand)GetValue(RemoveCommandProperty); } 
    set { SetValue(RemoveCommandProperty, value); } 
} 

public static readonly DependencyProperty LBItemsProperty = 
DependencyProperty.Register("LBItems", typeof(IEnumerable), typeof(ListBoxControl), null); 

public IEnumerable LBItems 
{ 
    get { return (IEnumerable)GetValue(LBItemsProperty); } 
    set { SetValue(LBItemsProperty, value); } 
} 

我使用这个控制这样的观点:

<ItemControls:ListBoxControl Height="240" Width="350" LBItems="{Binding Items, Converter={StaticResource ItemsConverter}, Mode=TwoWay}" RemoveCommand="{Binding RemoveCommand}"/> 

命令工作正常,但列表框绑定不。我的问题是 - 为什么?

回答

3

UserControl中的ListBox没有正确绑定到LBItems。 ListBox的DataContext不是你的控件,所以它试图直接从你的ViewModel绑定LBItems。

在您的UserControl声明中添加DataContext="{Binding RelativeSource={RelativeSource Self}}"。这应该正确地将您的DataContext设置为UserControl,并允许您绑定正确定位LBItems属性。

编辑

您的评论提醒我。您需要将网格的DataContext设置为您的UserControl。要做到这一点最简单的方法是命名网格即<Grid x:Name="LayoutRoot">,然后在构造函数中为您的用户控件LayoutRoot.DataContext = this;

如果你设置你从你的VM打破绑定的用户控件的DataContext的,但如果你把它们放在网格顶级绑定仍然可以正常工作,并且UserControl内的所有控件都可以正确绑定到UserControl。

+0

我已经在今天早些时候尝试了这个代码(this.DataContext = this在初始化),只是试过这个建议,但仍然没有运气。 – Walkor 2010-06-01 13:51:44

+0

我想我知道这个问题。编辑我的答案来展示。 – Stephan 2010-06-01 15:07:45

+0

太棒了!非常感谢,斯蒂芬。你做了我的一天,我花了10个小时。 – Walkor 2010-06-01 15:45:41