私はXAMLでこれを行う方法が見つかりませんでしたが、これはコードの背後にありました。ここで私が取ったアプローチです。
まず、ItemsControl
のすべての商品についてこれを行いたいと思います。だから私はこのようにXAMLを持っていた:
その後
<ListBox x:Name="_events" ItemsSource="{Binding Path=Events}">
<ListBox.ItemTemplate>
<DataTemplate DataType="{x:Type Events:EventViewModel}">
<TextBlock Name="ActualText" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
、建設の背後にあるコードでは、私はItemContainerGenerator
を購読する:
InitializeComponent();
_events.ItemContainerGenerator.StatusChanged
+= OnItemContainerGeneratorStatusChanged;
このメソッドは次のようになります。あなたが唯一持っている場合は
private void OnItemContainerGeneratorStatusChanged(object sender, EventArgs e)
{
if (_events.ItemContainerGenerator.Status!=GeneratorStatus.ContainersGenerated)
return;
for (int i = 0; i < _viewModel.Events.Count; i++)
{
// Get the container that wraps the item from ItemsSource
var item = (ListBoxItem)_events.ItemContainerGenerator.ContainerFromIndex(i);
// May be null if filtered
if (item == null)
continue;
// Find the target
var textBlock = item.FindByName("ActualText");
// Find the data item to which the data template was applied
var eventViewModel = (EventViewModel)textBlock.DataContext;
// This is the path I want to bind to
var path = eventViewModel.BindingPath;
// Create a binding
var binding = new Binding(path) { Source = eventViewModel };
textBlock.SetBinding(TextBlock.TextProperty, binding);
}
}
バインディングを設定する単一の項目を使用すると、コードはかなり簡単になります。
<TextBlock x:Name="_text" Name="ActualText" />
そして、背後にあるコードで:
var binding = new Binding(path) { Source = bindingSourceObject };
_text.SetBinding(TextBlock.TextProperty, binding);
誰かに役立ちます願っています。
私は同じことをしようとしています。私は、カスタムマークアップの拡張が役に立つかもしれないのだろうかと思っていますが、Pathは依存関係のプロパティではないので、これがどのように機能するかはわかりません。 –