我有一个用户控件,其中包含一个列表框和几个按钮。用户控件与列表框和父控件(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}"/>
命令工作正常,但列表框绑定不。我的问题是 - 为什么?
我已经在今天早些时候尝试了这个代码(this.DataContext = this在初始化),只是试过这个建议,但仍然没有运气。 – Walkor 2010-06-01 13:51:44
我想我知道这个问题。编辑我的答案来展示。 – Stephan 2010-06-01 15:07:45
太棒了!非常感谢,斯蒂芬。你做了我的一天,我花了10个小时。 – Walkor 2010-06-01 15:45:41