2015-04-26 62 views
0

是否可以直接在我的視圖中更改用戶控件的顏色?更改用戶控件的顏色

<local:MyControl 
    // properties 
/> 

我試過使用「前景」屬性,但它不起作用。

回答

0

您可以簡單地更改您的UserControl的任何屬性。例如:

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

要做到這一點,在控件中處理這些屬性(或進一步的自定義屬性)是很必要的。 BackgroundForeground適用於它自己的控件。但是,您也可以將其他控件屬性綁定到這些顏色/筆刷屬性。

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

如果你在你控制用戶控件中的孩子控件(如文本框),那麼你可以綁定自己的前景屬性來控制的前景。 Examlpe:

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

如果用戶控件不執行任何基本類型類別(例如FrameworkElement的,或用戶控件),那麼你必須創建前景屬性,如果你想WPF結合得使用,也它的正派特性。 代碼在MyControl.xaml.cs:

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

在第二種情況下,你也應該實現INotifyPropertyChanged接口用於更新WPF控件。