gpt4 book ai didi

c# - 在 UserControl 中设置 ForegroundColor

转载 作者:太空狗 更新时间:2023-10-30 01:07:18 26 4
gpt4 key购买 nike

我正在用 WPF 编写一个用户控件,这是我的第一个自己的控件。供您引用,我正在使用 Telerik 控件。

我的用户控件只是一个 Grid,它只包含 2 个 GridView。现在我想让某人可以通过设置前景和背景来设置 GridView 的样式。

我都是这样设置的:

Background="{Binding ElementName=Grid, Path=DarkBackground}"
Foreground="{Binding ElementName=Grid, Path=LightForeground}"

我背后的代码是:

public static DependencyProperty LightForegroundProperty = DependencyProperty.Register( "LightForeground", typeof( Brush ), typeof( ParameterGrid ) );
public Brush LightForeground
{
get
{
return (Brush)GetValue( LightForegroundProperty );
}
set
{
SetValue( LightForegroundProperty, value );
}
}

public Brush DarkBackground
{
get
{
return (Brush)GetValue( DarkBackgroundProperty );
}
set
{
SetValue( DarkBackgroundProperty, value );
}
}

问题是我的前景,背景值在运行时被忽略了。为 Foreground 设置固定值会带来预期的结果。

我没有发现我的错误,有人有想法吗???

最佳答案

所以澄清一下...您有一个 UserControl,里面有一个 Grid 和 2 个 GridViews

要引用 UserControl 上的依赖属性...可以通过不同的方式完成。

将 DataContext 设置为自身(代码隐藏)

在您的 UserControl 的构造函数中,将 DataContext 设置为指向您的 UserControl 实例。

DataContext = this;

然后像这样访问您的属性:

Background="{Binding DarkBackground}"
Foreground="{Binding LightForeground}"

将 DataContext 设置为自身 (XAML)

如果您不想通过代码隐藏来完成,那么您可以使用 XAML。

<UserControl DataContext="{Binding RelativeSource={RelativeSource Self}}">

在您的 UserControl 和 ElementName 上使用名称来引用它

x:Name="MyUserControl" 放在您的 UserControl 上,然后用 ElementName 引用它。

Background="{Binding ElementName=MyUserControl, Path=DarkBackground}"
Foreground="{Binding ElementName=MyUserControl, Path=LightForeground}"

使用 RelativeSource 告诉 Binding 属性的来源。

通过使用 RelativeSource 在树中寻找 UserControl 来指定绑定(bind)的“源”。

Background="{Binding RelativeSource={RelativeSource AncestorType={x:Type UserControl}}, Path=DarkBackground}"
Foreground="{Binding RelativeSource={RelativeSource AncestorType={x:Type UserControl}}, Path=LightForeground}"

关于c# - 在 UserControl 中设置 ForegroundColor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13025768/

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