【发布时间】:2011-03-29 05:26:01
【问题描述】:
我的问题总结:我创建了一个UserControl,我将我的依赖属性“Scheme”绑定到GradientStop 的Color 属性,它运行良好。现在,将我的UserControl 转换为自定义控件后,此绑定不再起作用,我不知道为什么。
这就是我在 UserControl1.xaml 文件中为我的 UserControl 声明资源字典的方式。
在UserControl1.xaml:
<!-- Resources -->
<UserControl.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Colors.xaml"/>
<ResourceDictionary Source="Styles.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</UserControl.Resources>
在Colors.xaml 内,我有以下内容:
在Colors.xaml:
<GradientStopCollection x:Key="colorSchemeGradient">
<GradientStop Color="{Binding Scheme, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}}" Offset="0"/>
<GradientStop Color="#000000" Offset="3"/>
</GradientStopCollection>
<LinearGradientBrush x:Key="colorBrush" StartPoint="0,0" EndPoint="0,1" GradientStops="{DynamicResource colorSchemeGradient}"/>
依赖属性 Scheme 与 GradientStop 的 color 属性的绑定完美地工作,正是我想要的。 LinearGradientBrush 使用方案颜色来创建从方案颜色到稍暗的渐变。
UserControl 中有一个矩形,它使用 colorBrush 作为其背景。这一切都很完美,我喜欢它。
现在,情况让我将这个UserControl 转换为CustomControl。我通过获取我的 UserControl 的 XAML 文件并将其所有内容复制到控制模板中的 Generic.xaml 中来做到这一点。
在尝试了不同的事情之后,这对于在Generic.xaml 中声明我的资源字典似乎非常有效:
在Generic.xaml:
<Style TargetType="{x:Type local:MyCustomControl}">
<!-- Style Resources -->
<Style.Resources>
<!-- Resource Dictionaries -->
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/MyCustomControl;component/themes/Colors.xaml"/>
<ResourceDictionary Source="/MyCustomControl;component/themes/Styles.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Style.Resources>
.
.
.
</Style>
现在,在我的 Colors.xaml 文件中,我有以下内容:
在Colors.xaml 中用于我的自定义控件:
<GradientStopCollection x:Key="colorSchemeGradient">
<GradientStop Color="{Binding Path=Scheme, RelativeSource={RelativeSource FindAncestor, AncestorType=l:MyCustomControl}}" Offset="0"/>
<GradientStop Color="#000000" Offset="3"/>
</GradientStopCollection>
<!-- FOR DEBUG PURPOSES -->
<TextBlock x:Key="whoaText" Text="{Binding Path=Title, RelativeSource={RelativeSource FindAncestor, AncestorType=l:MyCustomControl}}"/>
<LinearGradientBrush x:Key="colorBrush" StartPoint="0,0" EndPoint="0,1" GradientStops="{DynamicResource colorSchemeGradient}"/>
现在,由于某些我无法理解的非常令人沮丧的原因,绑定到 GradientStop 不再起作用。我组织资源的方式没有问题,因为我制作的调试文本块完美地绑定到 Title 依赖属性。
GradientStop 颜色没有绑定到 Scheme 依赖属性,这让我很烦。
我该如何解决?
在Dictionary1.xaml 中查看带有x:key "text2" 的文本块。 colorBrush 使用来自colorSchemeGradient 的渐变色标,它使用与Scheme 的绑定。但是,该绑定失败,因此没有任何效果。如果您可以使该绑定正常工作,那就太棒了。
为什么绑定在这里起作用,而不是在自定义控件中?
【问题讨论】:
-
您能否添加一些代码,例如您的 CustomControl 的 XAML,以便我们可以清楚地看到绑定失败的位置。 {享受}
-
我编辑了我的帖子以包含一个链接,该链接指向一个测试项目的链接,该链接用于绑定不起作用的自定义控件,并且我还包含了一个指向绑定有效的测试用户控件的链接。这里发生了什么?希望你有机会去看看。
标签: c# wpf custom-controls binding dependency-properties