M. *_*ley 7 wpf xaml binding resourcedictionary
我如何UserControl从其内部绑定一个属性ResourceDictionary?我想要一个我在我的资源中声明的对象DataContext与UserControl它包含在的对象相同:
<UserControl
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:Some.Namespace"
DataContext="{Binding Path=ViewModel, RelativeSource={RelativeSource Self}}">
<UserControl.Resources>
<local:SomeClass
x:Key="SomeClass"
DataContext="{Binding Path=DataContext, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}}" />
</UserControl.Resources>
</UserControl>
Run Code Online (Sandbox Code Playgroud)
在运行时我收到错误:
System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='UserControl', AncestorLevel='1''. BindingExpression:Path=DataContext; DataItem=null; target element is 'SomeClass' (Name=''); target property is 'DataContext' (type 'Object')
我的解决方法是DataContext在代码隐藏中设置资源的。
.xaml
<local:SomeType x:Key="SomeKey" SomeProperty="{Binding ... }" />
Run Code Online (Sandbox Code Playgroud)
.xaml.cs
<local:SomeType x:Key="SomeKey" SomeProperty="{Binding ... }" />
Run Code Online (Sandbox Code Playgroud)