【问题标题】:Setting ForegroundColor in a UserControl在 UserControl 中设置 ForegroundColor
【发布时间】:2012-10-23 07:49:49
【问题描述】:

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

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

我都是这样设置的:

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 设置一个固定值会带来预期的结果。

我没有发现我的错误,有人知道吗???

【问题讨论】:

  • 现在我知道这是一个绑定问题。 Snoop 告诉我:> System.Windows.Data 错误:4:找不到与引用“ElementName = Grid”进行绑定的源。 BindingExpression:Path=LightForeground ;数据项=空;目标元素是'TextBlock'(名称='');目标属性是“前景”(类型“画笔”)

标签: c# wpf user-controls wpf-controls foreground


【解决方案1】:

所以澄清一下……你有一个UserControl,里面有一个Grid,还有2个GridViews

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

将 DataContext 设置为 Self(代码隐藏)

在您的 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来指定​​Binding的“来源”。

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

【讨论】:

  • 非常感谢。我现在用的是RelativeSource的方式。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-06-25
  • 2021-02-11
  • 1970-01-01
  • 1970-01-01
  • 2021-07-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多