gpt4 book ai didi

wpf - 绑定(bind) GradientStop 有效但报告错误

转载 作者:行者123 更新时间:2023-12-04 12:56:23 25 4
gpt4 key购买 nike

以下代码绑定(bind)了 GradientStopBackground.Color TemplatedParent 的属性(property).一切正常,但我在输出窗口中遇到绑定(bind)错误:

System.Windows.Data Error: 2 : Cannot find governing FrameworkElement or FrameworkContentElement for target element. BindingExpression:Path=Background.Color; DataItem=null; target element is 'GradientStop' (HashCode=6944299); target property is 'Color' (type 'Color')


<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="WpfBindingTest.MainWindow"
x:Name="Window"
Title="MainWindow"
Width="100" Height="100">
<Window.Resources>
<ControlTemplate x:Key="GradientTemplate" TargetType="{x:Type ContentControl}">
<Border BorderThickness="1" BorderBrush="{TemplateBinding Background}">
<Border.Background>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="{Binding Path=Background.Color,
RelativeSource={RelativeSource TemplatedParent}}" Offset="1"/>
<GradientStop Color="White" Offset="0"/>
</LinearGradientBrush>
</Border.Background>
<ContentPresenter/>
</Border>
</ControlTemplate>
</Window.Resources>

<Grid x:Name="LayoutRoot">
<ContentControl Background="Green" Template="{StaticResource GradientTemplate}" >
<TextBlock VerticalAlignment="Center" HorizontalAlignment="Center" Text="X" />
</ContentControl>
</Grid>
</Window>

最佳答案

我在 Visual Studio 控制台输出中也遇到了同样的错误。

报告了一个可能的解释和解决方法 here

基本上,如果您使用返回 LinearGradientBrush 的转换器,那么您不会收到错误消息

代码是这样的

[ValueConversion(typeof(System.Windows.Media.Color), typeof(LinearGradientBrush))]
class GradientConverter : IValueConverter
{

public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
var brush = new LinearGradientBrush();
var color = (Color)value;
brush.StartPoint = new Point(0.5, 0);
brush.EndPoint = new Point(0.5, 1);

brush.GradientStops.Add(new GradientStop(Colors.White, 0));
brush.GradientStops.Add(new GradientStop((Color)value, 1));

return brush;
}

public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}

在 XAML 中
<Border BorderThickness="1" BorderBrush="{TemplateBinding Background}" Background="{Binding Path=Background.Color, RelativeSource={RelativeSource TemplatedParent}, Converter={StaticResource gradConv}}">

关于wpf - 绑定(bind) GradientStop 有效但报告错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3882767/

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