1
私はUserControlをDataTemplateとして使用しているListBoxを持っています。私のUserControlにはViewModelがあります。私は私のUserControlに私のListBoxからアイテムをバインドできるように私の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を設定することができますエンジンは、コントロールを含むDataContextの代わりにUserControlで設定されたDataContextを使用します(この場合、ListBoxによって生成されます)。なぜXAMLでDataContextを設定するのがコードと違うのですか? – serine