1
DataController로 UserControl을 사용하는 ListBox가 있습니다. 내 UserControl ViewModel 있습니다. 내 ListBox에서 내 UserControl에 항목을 바인딩 할 수 있도록 내 UserControl에 DependencyProperty가 있습니다.DataContext를 사용하는 UserControl의 DependencyProperty
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 : 목록 상자에서 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 클래스 :
public class MyClass : INotifyPropertyChanged
{
public String FromParent { get; set; }
...
}
내가 뭘 잘못 했니? 여기
을 포함하기 위해 필요한이
처럼의 DataContext를 설정할 수 있지만, 문제는 왜 구속력을 설정하는 엔진은 포함 된 컨트롤 (이 경우 ListBox에 의해 생성 됨)의 DataContext 대신 UserControl에 설정된 DataContext를 사용합니까? XAML에서 DataContext를 설정하는 것이 코드에서와 다르게 작동하는 이유는 무엇입니까? – serine