WPF绑定:属性包含值的路径

我在顶部栏中有一个带有几个TextBlocks的扩展器,我用它来给出一个标题和一条关键信息。

理想情况下,我想设置关键信息的路径,但我无法弄清楚如何将绑定路径绑定到另一条路径(如果我没有多大意义,我道歉!)

在下面的xaml第一位工作,第二位是我正在努力的。

  

KeyValuePath可能包含类似“Vehicle.Registration”或“Supplier.Name”的内容,具体取决于Model。

有人能指出我正确的方向吗? 任何帮助感激不尽!

我不认为它可以在纯XAML中完成… Path不是DependencyProperty(并且无论如何Binding不是DependencyObject),所以它不能成为绑定的目标

您可以修改代码隐藏中的绑定

我还没有找到在XAML中执行此操作的方法,但我在后面的代码中执行了此操作。 这是我采取的方法。

首先,我想对ItemsControl所有项目执行此操作。 所以我有这样的XAML:

        

然后,在构造后面构建我订阅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); } } 

如果您只有一个项目来设置绑定,那么代码将更加简单。

  

在代码背后:

 var binding = new Binding(path) { Source = bindingSourceObject }; _text.SetBinding(TextBlock.TextProperty, binding); 

希望能帮助别人。