mskuratowski
mskuratowski

Reputation: 4124

Change color of user control

Is possible to change color of user control directly in my view ?

<local:MyControl
  // properties
/>

I've tried use "Foreground" property, but it doesn't work.

Upvotes: 2

Views: 7472

Answers (2)

nvi9
nvi9

Reputation: 1893

If you have children controls inside the user control (eg. textboxes) in your control, then you can bind their foreground property to the control's foreground. Example:

<local:MyControl>
  <TextBox Foreground="{Binding Foreground, RelativeSource={RelativeSource AncestorType={x:Type local:MyControl}}}"/>
  <TextBlock Foreground="the same binding"/>
  ...
</local:MyControl>

If the user control doesn't implements any base type class (eg. FrameworkElement or UserControl), then you have to create the Foreground property, and if you want to use WPF binding too, also the decency property for it. Code in MyControl.xaml.cs:

    public static readonly DependencyProperty ForegroundProperty = DependencyProperty.Register("Foreground", typeof(Brush), typeof(MyControl));
    public Brush Foreground {
      get { return (Brush)GetValue(ForegroundProperty); }
      set { SetValue(ForegroundProperty, value); }
    }

In the second case you should also implement INotifyPropertyChanged interface for updating the WPF control properly.

Upvotes: 5

Koopakiller
Koopakiller

Reputation: 2883

You can simple Change any property of your UserControl. For example:

<local:MyControl Foreground="Red" Background="#FF008080"/>

To make this work it is necassary to process these properties (or further custom properties) in the control. Background and Foreground is applied to the control it self. But you can also bind other control properties to These color/brush properties.

<Button Background="{Binding Background, ElementName=myBindingTarget}" />
<!-- or some other binding -->
<Button Background="{Binding }"/>

Upvotes: 0

Related Questions