WPF DataContextProxy в разделе ресурсов
У меня возникли проблемы с использованием DataContextProxy в моем приложении WPF. Когда я помещаю DataContextProxy в раздел «Ресурсы» сетки, он никогда не загружается. Если я перемещаю DataContextProxy из раздела ресурсов, все работает правильно.
Я изучал это в течение некоторого времени и попробовал несколько методов для отладки приложения.
I’ve placed a DebugConverter on the control that I’m trying to use the Proxy with. The Debug converter is never called.
I’ve used WPFSnoop to see if there are any binding errors. I get the following binding error on the DataContextProxy,
System.Windows.Data Error: 3 : Cannot find element that provides DataContext. BindingExpression:(no path); DataItem=null; target element is 'Proxy' (Name=''); target property is 'DataContext' (type 'Object')
I’ve placed a breakpoint on the loaded event of my DataContextProxy. The loaded event is never called and I’ve placed a breakpoint in the DataContextChanged event which is never called.
Вот пример кода, чтобы продемонстрировать это. Очевидно, я знаю, что мне не нужно использовать DataContextProxy в TextBox.
<code><Window x:Class="WpfDataContextProxyBug.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:WpfDataContextProxyBug" Title="MainWindow" Height="350" Width="525"> <Window.Resources> <local:DebugConverter x:Key="DebugConverter"/> </Window.Resources> <Grid> <Grid.Resources> <local:Proxy x:Key="Proxy" DataContext="{Binding}" /> </Grid.Resources> <TextBox DataContext="{Binding Path=Name, Source={StaticResource Proxy}, Converter={StaticResource DebugConverter}}"/> </Grid> </Window> </code>
Класс DataContextProxy
<code>public class Proxy : FrameworkElement { public Proxy() { Loaded += DataContextProxy_Loaded; DataContextChanged += Proxy_DataContextChanged; } void Proxy_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e) { } void DataContextProxy_Loaded(object sender, RoutedEventArgs e) { } } </code>