2010-06-01 8 views
0

나는 Listbox와 몇 개의 버튼이 포함 된 UserControl을 가지고 있습니다. UserControl과 목록 상자 및 부모 컨트롤 (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가 LBItem에 올바르게 바인딩되지 않습니다. ListBox의 DataContext는 사용자의 컨트롤이 아니므로 ViewModel에서 LBItem을 직접 바인딩하려고합니다.

UserControl 선언에 DataContext="{Binding RelativeSource={RelativeSource Self}}"을 추가하십시오. 그게 제대로 UserControl에 DataContext를 설정하고 LBItems 속성을 올바르게 찾을 수 있도록 바인딩을 허용해야합니다.

편집

귀하의 의견은 나에게 상기시켰다. Grid의 DataContext를 UserControl로 설정해야합니다. 이 작업을 수행하는 가장 간단한 방법은 이름을 그리드 즉 <Grid x:Name="LayoutRoot">하고 다음 그리드를 설정하면 당신은 당신의 VM에서 바인딩을 깰 해당 UserControl의 DataContext를 설정하지만, 경우 UserControl을 LayoutRoot.DataContext = this;

의 생성자 최상위 바인딩 여전히 작동하고 UserControl 내부의 모든 컨트롤을 올바르게 UserControl 바인딩 할 수 있습니다.

+0

나는이 코드를 오늘 일찍 시도했지만 (this.DataContext = 초기화에서)이 제안을 시도했지만 여전히 운이 없다. – Walkor

+0

나는 그 문제를 안다고 생각한다. 표시 할 내 답변을 수정했습니다. – Stephan

+0

굉장! 많은 고마워요, 스테판 너는 내 하루를 보냈고, 나는 이것에 10 시간을 보냈다. – Walkor