在UserControl中设置ForegroundColor

Suk*_*ram 4 c# wpf user-controls foreground wpf-controls

我在WPF中编写用户控件,这是我自己的第一个控件.对于您的信息,我使用Telerik控件.

我的用户控件Grid只包含2 GridView秒.而现在我想GridView通过设置前景和背景给某人设置样式的可能性.

我都是这样设定的:

Background="{Binding ElementName=Grid, Path=DarkBackground}"
Foreground="{Binding ElementName=Grid, Path=LightForeground}"
Run Code Online (Sandbox Code Playgroud)

我的代码背后是:

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 );
  }
}
Run Code Online (Sandbox Code Playgroud)

问题是我的前景,背景值在运行时被忽略.要为Foreground设置修复值,会带来预期结果.

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

Col*_*ith 5

所以要澄清......你有UserControl一个Grid内部和2 GridViews.

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

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

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

DataContext = this;
Run Code Online (Sandbox Code Playgroud)

然后访问您的属性,如下所示:

Background="{Binding DarkBackground}"
Foreground="{Binding LightForeground}"
Run Code Online (Sandbox Code Playgroud)

将DataContext设置为Self(XAML)

如果您不想通过代码隐藏来执行此操作,则可以使用XAML.

<UserControl DataContext="{Binding RelativeSource={RelativeSource Self}}">
Run Code Online (Sandbox Code Playgroud)

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

穿上x:Name="MyUserControl"你的UserControl,然后用它来引用它ElementName.

Background="{Binding ElementName=MyUserControl, Path=DarkBackground}"
Foreground="{Binding ElementName=MyUserControl, Path=LightForeground}"
Run Code Online (Sandbox Code Playgroud)

使用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}"
Run Code Online (Sandbox Code Playgroud)