使单个方法适用于多个WPF元素

时间:2019-06-17 03:07:16

标签: c# wpf xaml

我创建了一个单击事件/方法,该事件/方法更改了文本框的不透明度和IsEnabled属性。

private void EditButton(object sender, RoutedEventArgs e)
{
   religionTB.IsEnabled = true;

   DoubleAnimation fade = new 
   DoubleAnimation(1,TimeSpan.FromSeconds(0.2));
   religionTB.BeginAnimation(OpacityProperty, fade);
}

在我的WPF项目中,有多个文本框,我想将此方法应用于所有这些文本框,而不必在方法中列出所有文本框。我该怎么办?

1 个答案:

答案 0 :(得分:0)

您可以使用Style来实现。为此,请转到事件处理程序(ControlWindow)的上下文并添加一个DependencyProperty,以标记启用的模式并绑定一个ToggleButton(编辑按钮)来设置此属性,以启用/禁用控件并触发淡入和淡出动画:

在您的控制范围内:

public static readonly DependencyProperty IsEditEnabledProperty = DependencyProperty.Register(
  "IsEditEnabled",
  typeof(bool),
  typeof(MainWindow),
  new PropertyMetadata(default(bool)));

public bool IsEditEnabled { get { return (bool) GetValue(MainWindow.IsEditEnabledProperty); } set { SetValue(MainWindow.IsEditEnabledProperty, value); } }

在XAML中,添加TextBox样式并将ToggleButton链接到IsEditEnabled

<Window.Resources>
  <Style x:Key="OpacityStyle" TargetType="TextBox">
    <Setter Property="Opacity" Value="0" />
    <Setter Property="IsEnabled" 
            Value="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=Window}, Path=IsEditEnabled}" />

    <Style.Triggers>
      <DataTrigger Binding="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=Window}, Path=IsEditEnabled}"
                   Value="True">

        <! Fade in animation -->
        <DataTrigger.EnterActions>
          <BeginStoryboard>
            <Storyboard>
              <DoubleAnimation Storyboard.TargetProperty="Opacity"
                                   BeginTime="0:0:0"
                                   From="0"
                                   To="1"
                                   Duration="0:0:0.2" />
            </Storyboard>
          </BeginStoryboard>
        </DataTrigger.EnterActions>

        <! Fade out animation -->
        <DataTrigger.ExitActions>
          <BeginStoryboard>
            <Storyboard>
              <DoubleAnimation Storyboard.TargetProperty="Opacity"
                                   BeginTime="0:0:0"
                                   From="1"
                                   To="0"
                                   Duration="0:0:0.2" />
            </Storyboard>
          </BeginStoryboard>
        </DataTrigger.ExitActions>        
      </DataTrigger>
    </Style.Triggers>
  </Style>
</Window.Resources>

<Grid>
  <StackPanel>
    <ToggleButton x:Name="EditButton" IsChecked="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=Window}, Path=IsEditEnabled, Mode=TwoWay}" />
    <TextBox x:Name="AnimatedTextBox" Style="{StaticResource TextBoxAnimationStyle}" >
    <TextBox x:Name="AnotherAnimatedTextBox" Style="{StaticResource TextBoxAnimationStyle}" >
    <TextBox x:Name="NonanimatedTextBox" >
  </StackPanel>
</Grid>

如果通过删除Style属性使x:Key隐式,它将应用于范围内的所有TextBox元素