2012-02-26 55 views
2

我正在编写一个名为MyUserControl的自定义用户控件。我有很多DependecyProperties,我在MainWindow中使用了多个MyUserControl。我想知道的是如何创建风格的触发器/属性触发的自定义属性?触发器的用户控件自定义属性

例如,如果我有一个自定义属性BOOL IsGoing和自定义属性MyBackgroung(该用户控件的背景),两者都定义为:

public bool IsGoing 
    { 
     get { return (bool)this.GetValue(IsGoingProperty); } 
     set { this.SetValue(IsGoingProperty, value); } 
    } 
    public static readonly DependencyProperty IsGoingProperty = DependencyProperty.RegisterAttached(
     "IsGoing", typeof(bool), typeof(MyUserControl), new PropertyMetadata(false)); 

public Brush MyBackground 
    { 
     get { return (Brush)this.GetValue(MyBackgroundProperty); } 
     set { this.SetValue(MyBackgroundProperty, value); } 
    } 
    public static readonly DependencyProperty MyBackgroundProperty = DependencyProperty.Register(
      "MyBackground", typeof(Brush), typeof(MyUserControl), new PropertyMetadata(Brushes.Red)); 

,如果我定义MainWindow.xaml我的用户,我如何访问触发器并设置MyBackground,取决于IsGoing属性是否为真/假? 我试过很多东西,但在本质上,我想实现的东西,如:

<custom:MyUserControl MyBackground="Green" x:Name="myUC1" Margin="120.433,0,0,65.5" Height="50" Width="250" VerticalAlignment="Bottom" HorizontalAlignment="Left" > 
     <Style> 
      <Style.Triggers> 
       <Trigger Property="IsGoing" Value="True"> 
        <Setter Property="MyBackground" Value="Yellow"/> 
       </Trigger> 
      </Style.Triggers> 
     </Style> 
    </custom:MyUserControl> 

我希望我的解释是不够好,让你了解。我已经为此工作了几天,而且我似乎无法找到解决方案。 感谢您的帮助!

阿德里安

回答

3

你的风格应该只需要被用作UserControl.Style并且具有正确的TargetType,你也打算通过触发改变需要被移动到适当的风格precedence默认值:

<custom:MyUserControl.Style> 
    <Style TargetType="custom:MyUserControl"> 
     <Setter Property="MyBackground" Value="Green"/> 
     <Style.Triggers> 
      <Trigger Property="IsGoing" Value="True"> 
       <Setter Property="MyBackground" Value="Yellow"/> 
      </Trigger> 
     </Style.Triggers> 
    </Style> 
</custom:MyUserControl.Style> 

是否实际上确实什么都取决于您如何使用控件定义中的属性。

+1

谢谢!它的工作:) ...哇,我简直不敢相信这是简单的。经过几天的努力,并且几乎是一样的东西,只有修改了几行......我简直不敢相信......谢谢! – 2012-02-26 21:51:28

相关问题