2010-12-06 103 views
1

我有一個公開的公共屬性這樣的用戶控件:用戶控件的屬性

public Double ButtonImageHeight 
{ 
    get { return imgButtonImage.Height; } 
    set { imgButtonImage.Height = value; } 
} 

當我使用該控件,我希望能夠設置該屬性throught一個風格類似:

<Style x:Key="MyButtonStyle" TargetType="my:CustomButtonUserControl" > 
    <Setter Property="ButtonImageHeight" Value="100" /> 
</Style> 

我在做什麼錯?

感謝

+1

顯示xaml實際上將UserControl放置在另一個位置以及如何爲其分配樣式。 – AnthonyWJones 2010-12-06 14:16:40

回答

1

屬性必須是依賴屬性以支持樣式。

3

感謝Matt,我只是自己找到了它,但你是絕對正確的...下面是我使用的確切代碼,以防它可以幫助其他人(我發現的所有示例都在WPF上,silverlight只是略有不同):

public static readonly DependencyProperty ButtonImageHeightProperty = DependencyProperty.Register("ButtonImageHeight", typeof(Double), typeof(CustomButtonUserControl),new PropertyMetadata(ButtonImageHeight_PropertyChanged)); 

public Double ButtonImageHeight 
{ 
    get { return (Double)GetValue(ButtonImageHeightProperty); } 
    set { SetValue(ButtonImageHeightProperty, value); } 
} 

private static void ButtonImageHeight_PropertyChanged(DependencyObject source, DependencyPropertyChangedEventArgs e) 
{ 
    ((CustomButtonUserControl)source).imgButtonImage.Height = (Double)e.NewValue; 
} 
0

通過爲imgButtonImage傳遞樣式,您可以使它更通用,更好,這樣您可以設置多個屬性。所以,你的用戶控件中添加依賴屬性,而是使之成爲風格:

public static readonly DependencyProperty UseStyleProperty = 
     DependencyProperty.Register("UseStyle", typeof(Style), typeof(CustomButtonUserControl), new PropertyMetadata(UseStyle_PropertyChanged)); 

    public Style UseStyle 
    { 
     get { return (Style)GetValue(UseStyleProperty); } 
     set { SetValue(UseStyleProperty, value); } 
    } 

    private static void UseStyle_PropertyChanged(DependencyObject source, DependencyPropertyChangedEventArgs e) 
    { 
     ((CustomButtonUserControl)source).imgButtonImage.Style = (Style)e.NewValue; 
    } 

注意如何的PropertyChanged函數中我控制的樣式設置爲新的樣式。

然後當我主持用戶控件,我可以通過風格:

<Style x:Name="MyFancyStyle" TargetType="Button" > 
    <Setter Property="FontSize" Value="24" /> 
</Style> 

<controls:MyUserControl UseStyle="{StaticResource MyFancyStyle}" /> 

作品在VS設計模式呢! (這是一個奇蹟