2011-02-03 61 views
1

我有一个ListBox,我使用UserControl作为DataTemplate。我的UserControl有一个ViewModel。我在我的UserControl中有一个DependencyProperty,以便我可以将ListBox中的项目绑定到我的UserControl。用于UserControl的DependencyProperty与DataContext

它不起作用,除非我没有设置任何DataContext到我的UserControl。

如何在我的UC中使用DP和自定义DataContext?

我的列表框:

<ListBox ItemsSource="{Binding Path=ListItems, Mode=TwoWay}"> 
    <ListBox.ItemTemplate> 
     <DataTemplate> 
      <Grid> 
       <local:MyCustomUC MyObject="{Binding Path=.}"/> 
      </Grid> 
     </DataTemplate> 
    </ListBox.ItemTemplate> 
</ListBox> 

我的用户XAML:

<UserControl x:Class="UserControlDataTemplate.MyCustomUC" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Height="Auto" Width="Auto"> 
    <StackPanel Orientation="Horizontal"> 
     <TextBlock Text="{Binding Path=FromViewModel}" /> 
     <Button Content="{Binding ElementName=MyObject, Path=FromParent}" /> 
    </StackPanel> 
</UserControl> 

我的用户CS:在的ItemSource

 public MyClass MyObject 
     { 
      get { return (MyClass)GetValue(MyObjectProperty); } 
      set 
      { 
       SetValue(MyObjectProperty, value); 
      } 
     } 

     // Using a DependencyProperty as the backing store. This enables animation, styling, binding, etc... 
     public static readonly DependencyProperty MyObjectProperty = 
     DependencyProperty.Register("MyObject", typeof(MyClass), typeof(MyCustomUC), new PropertyMetadata(null)); 

     public MyCustomUC() 
     { 
      InitializeComponent(); 

      this.DataContext = new MyCustomUCViewModel(); 
     } 

My ViewModel: 

    public class MyCustomUCViewModel : DependencyObject, INotifyPropertyChanged 
    { 
     public String FromViewModel { get; set; } 

     public MyCustomUCViewModel() 
     { 
      this.FromViewModel = Guid.NewGuid().ToString(); 
     } 
     ... 
    } 

Item类从Control:

public class MyClass : INotifyPropertyChanged 
{ 
    public String FromParent { get; set; } 
    ... 
} 

我做错了什么?

回答

1

这里要设置在MyCustomUC()在DataContext
相反,你可以设置的DataContext像这样

<vm:YourViewModel x:Name="VModel" IfPropertToSet="{BindingFromExistingDC}"/> 

<ListBox ItemsSource="{Binding Path=ListItems, Mode=TwoWay}"> 
    <ListBox.ItemTemplate> 
     <DataTemplate> 
      <Grid> 
       <local:MyCustomUC MyObject="{Binding Path=.}" DataContext="{Binding ElementName=VModel}" /> 
      </Grid> 
     </DataTemplate> 
    </ListBox.ItemTemplate> 
</ListBox> 

您需要包括命名空间

xmlns:vm="clr-namespace:YourViewModelPath" 
+1

但问题是为什么绑定引擎使用在UserControl中设置的DataContext而不是包含控件的DataContext(在这种情况下由ListBox生成)?为什么在XAML中设置DataContext的工作方式与在代码中不同? – serine 2011-07-14 11:30:50

相关问题