我有一个ListBox,使用UserControl作为DataTemplate。我的UserControl有一个ViewModel。在我的UserControl中有一个DependencyProperty,这样我可以将来自ListBox的项目绑定到我的UserControl。
除非我不给我的UserControl设置任何DataContext,否则它不起作用。
我如何在我的UC中同时使用DP和自定义DataContext?
我的ListBox:
<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:
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();
}
...
}
从ListBox中的ItemSource获取的Item类:
public class MyClass : INotifyPropertyChanged
{
public String FromParent { get; set; }
...
}
我做错了什么?