WPF绑定:凡属性包含值的路径
问题描述:
我有一个扩展器,在顶部栏中有一对TextBlocks,我用它来给出一个标题和一个关键信息。WPF绑定:凡属性包含值的路径
理想情况下,我想设置关键信息的路径,但我不能解决如何将绑定的路径绑定到另一个路径(我道歉,如果我没有太大的意义!)
在下面的xaml中,第一位工作,第二位是我正在努力的。
<TextBlock Text="{Binding Path=Header.Title}"/>
<TextBlock Text="{Binding Path={Binding Path=Header.KeyValuePath}}"/>
KeyValuePath可能包含类似 “Vehicle.Registration” 或根据型号 “Supplier.Name”。
任何人都可以指出我正确的方向吗?任何帮助感激地收到!
答
我不认为它可以在纯XAML来完成...路径不是一个DependencyProperty(反正绑定是不是DependencyObject的),所以它不可能是一个结合
你的目标可以修改在代码隐藏的绑定,而不是
答
我还没有找到一种方法在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不是依赖项属性,因此我无法完全了解这将如何工作。 – 2009-07-21 16:37:23