gpt4 book ai didi

wpf - 从 ResourceDictionary 中绑定(bind)到祖先

转载 作者:行者123 更新时间:2023-12-04 12:38:29 24 4
gpt4 key购买 nike

如何绑定(bind)到 UserControl的属性(property)来自其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>

在运行时我收到错误:
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 ... }" />

.xaml.cs

public SomeControl()
{
InitializeComponent();
((SomeType)this.Resources["SomeKey"]).DataContext = this;
}

关于wpf - 从 ResourceDictionary 中绑定(bind)到祖先,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2074321/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com