2010-06-01 51 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