2013-08-07 88 views
7

好吧,我有一個WPF應用程序,其中有一個資源字典。在詞典中,我有一個Button看起來像這樣一個新的風格:WPF在控件中添加一個自定義屬性

<Style x:Key="MenuButtonStyle" TargetType="Button"> 
     <Setter Property="Template"> 
     <Setter.Value> 
      <ControlTemplate TargetType="{x:Type Button}"> 

       <Grid> 
        <Image x:Name="Imager" RenderOptions.BitmapScalingMode="HighQuality" Width="{TemplateBinding Width}" Height="{TemplateBinding Height}" Source="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Tag}" VerticalAlignment="Center" HorizontalAlignment="Center" Stretch="UniformToFill"/> 
       </Grid> 

       <ControlTemplate.Triggers> 
        <Trigger Property="IsMouseOver" Value="true"> 
         <Setter TargetName="Imager" Property="Width" Value="24" /> 
         <Setter TargetName="Imager" Property="Height" Value="24" /> 
        </Trigger> 
        <Trigger Property="IsPressed" Value="true"> 
         <Setter TargetName="Imager" Property="Width" Value="16" /> 
         <Setter TargetName="Imager" Property="Height" Value="16" /> 
        </Trigger> 
       </ControlTemplate.Triggers> 
      </ControlTemplate> 
     </Setter.Value> 
    </Setter> 
</Style> 

,並使用此麥粒腫在我的XAML這樣的:

<Button x:Name="Home" Style="{DynamicResource MenuButtonStyle}" Width="20" Height="20" Tag="\Images\Home.png"/> 
<Button x:Name="Settings" Style="{DynamicResource MenuButtonStyle}" Width="20" Height="20" Tag="\Images\Settings.png"/> 

現在我想要做的是,創建在順序命名OverWidthOverHeightButton風格的新屬性,使用這樣的:

<Trigger Property="IsMouseOver" Value="true"> 
    <Setter TargetName="Imager" Property="Width" Value= OVERWIDTH/> 
    <Setter TargetName="Imager" Property="Height" Value= OVERHEIGHT/> 
</Trigger> 

而在XAML:

<Button x:Name="Home" Style="{DynamicResource MenuButtonStyle}" Width="20" Height="20" Tag="\Images\Home.png" OVERWIDTH = "24"/> 

我甚至不知道這是否可能。我不想使用C#代碼中的Binding SomeIntenger。 在此先感謝。

回答

19

可以使用attached properties

public class Extensions 
{ 
    public static readonly DependencyProperty OverWidthProperty = 
     DependencyProperty.RegisterAttached("OverWidth", typeof(double), typeof(Extensions), new PropertyMetadata(default(double))); 

    public static void SetOverWidth(UIElement element, double value) 
    { 
     element.SetValue(OverWidthProperty, value); 
    } 

    public static double GetOverWidth(UIElement element) 
    { 
     return (double)element.GetValue(OverWidthProperty); 
    } 
} 

的XAML:

xmlns:extensions="clr-namespace:NAMESPACE FOR Extensions class" 

<Trigger Property="IsMouseOver" Value="true"> 
    <Setter Property="MinWidth" Value="{Binding Path=(extensions:Extensions.OverWidth), RelativeSource={RelativeSource Self}}"/> 
</Trigger> 

<Button extensions:Extensions.OverWidth="100" Width="10"/>