我有一个ListBox,我使用UserControl作为DataTemplate。我的UserControl有一个ViewModel。我的UserControl中有一个DependencyProperty,因此我可以将项目从我的ListBox绑定到我的UserControl。
除非我没有为UserControl设置任何DataContext,否则它不起作用。
如何在我的UC中使用DP和自定义DataContext?
我的列表框:
<ListBox ItemsSource="{Binding Path=ListItems, Mode=TwoWay}">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<local:MyCustomUC MyObject="{Binding Path=.}"/>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
我的UserControl 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>
我的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; }
...
}
我做错了什么?
答案 0 :(得分: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"