我在我的WPF应用程序中使用DataContextProxy遇到了麻烦。当我将DataContextProxy放在Grid的资源部分时,它从未加载。如果我将DataContextProxy移出资源部分,则一切正常。
我已经调查了一段时间,并尝试了许多方法来调试应用程序。
- 我在我尝试使用代理的控件上放置了DebugConverter。Debug转换器从未被调用。 - 我使用WPFSnoop查看是否有任何绑定错误。在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') - 我在我的DataContextProxy的loaded事件上放置了断点。loaded事件从未被调用,我在DataContextChanged事件中放置了断点,但也从未被调用。
以下是一些示例代码以演示此问题。显然,我知道我实际上不需要在TextBox上使用DataContextProxy。
DataContextProxy类
我已经调查了一段时间,并尝试了许多方法来调试应用程序。
- 我在我尝试使用代理的控件上放置了DebugConverter。Debug转换器从未被调用。 - 我使用WPFSnoop查看是否有任何绑定错误。在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') - 我在我的DataContextProxy的loaded事件上放置了断点。loaded事件从未被调用,我在DataContextChanged事件中放置了断点,但也从未被调用。
以下是一些示例代码以演示此问题。显然,我知道我实际上不需要在TextBox上使用DataContextProxy。
<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>
DataContextProxy类
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)
{
}
}