[英]WPF Binding: Where a property contains the path to the value
我在頂部欄中有一個帶有幾個TextBlocks的擴展器,我用它來給出一個標題和一條關鍵信息。
理想情況下,我想設置關鍵信息的路徑,但我無法弄清楚如何將綁定的路徑綁定到另一條路徑(如果我沒有多大意義,我道歉!)
在下面的xaml第一位工作,第二位是我正在努力的。
<TextBlock Text="{Binding Path=Header.Title}"/>
<TextBlock Text="{Binding Path={Binding Path=Header.KeyValuePath}}"/>
KeyValuePath可能包含類似“Vehicle.Registration”或“Supplier.Name”的內容,具體取決於Model。
有人能指出我正確的方向嗎? 任何幫助感激不盡!
我不認為它可以在純XAML中完成...路徑不是DependencyProperty(並且無論如何Binding不是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);
希望能幫助別人。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.