C# 样式中的按钮的事件

C# 样式中的按钮的事件,c#,wpf,controltemplate,wpf-style,C#,Wpf,Controltemplate,Wpf Style,因为WPF中没有NumericUpDown-控件,所以我使用样式创建了一个 <Style x:Key="NumericUpDown" TargetType="{x:Type TextBox}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type TextBox}"> <Grid Width="

因为WPF中没有
NumericUpDown
-控件,所以我使用样式创建了一个

<Style x:Key="NumericUpDown" TargetType="{x:Type TextBox}">
  <Setter Property="Template">
    <Setter.Value>
      <ControlTemplate TargetType="{x:Type TextBox}">
        <Grid Width="45" Height="20">
          <TextBox Name="txtBox"
                   TextAlignment="Right"
                   Height="20"
                   Width="30"
                   Margin="0,0,15,0"
                   MaxLength="1"
                   Text="{Binding RelativeSource={RelativeSource TemplatedParent},
                                  Path=Text}"/>
          <Button Name="btnUp"
                  Height="10"
                  Content="▲"
                  Width="15"
                  Margin="30,0,0,10"
                  FontSize="5"/>
          <Button Name="btnDown"
                  Height="10"
                  Content="▼"
                  Width="15"
                  Margin="30,10,0,0"
                  FontSize="5"/>
        </Grid>
      </ControlTemplate>
    </Setter.Value>
  </Setter>
</Style>

(样式代码在App.xaml中)


现在,我希望按钮更改
文本框中的值。但我无法设置他们的
OnClick
事件。是否可以在代码隐藏中设置它,这样我就不必为窗口中的每个控件创建样式?提前谢谢

我认为您应该为数字上下创建一个
UserControl
或自定义控件,并将逻辑放在后面的代码中。您也可以使用模板部件,将按钮命名为
PART\u ButtonUp
PART\u ButtonDown
,以指示这些按钮具有特定的行为。这遵循WPF的现有实践。一些来源:和)我想“用户控制”可能更好。这要容易得多。我很感激!