我正在创建一个数字小键盘作为自定义WPF控件。我正在构建自定义控件作为类库,它将包含在其他应用程序中。键盘有多个按钮,我需要连接到单个事件处理程序。事件处理程序将确定发送事件的按钮,然后进行适当的响应。自定义控件模板位于generic.xaml文件中。
我认为有两种方法可以做到这一点,并且想知道哪种方法被认为是更好的解决方案。
方法1:
我可以在我的自定义控件类中覆盖OnApplyTemplate方法,找到每个按钮,然后将它们连接到事件处理程序:
Button enterButton = Template.FindName("PART_EnterButton, this") as Button;
Button cancelButton = Template.FindName("PART_CancelButton", this) as Button;
Button deleteButton = Template.FindName("PART_DeleteButton", this) as Button;
Button decimalButton = Template.FindName("PART_DecimalButton", this) as Button;
Button buttonOne = Template.FindName("PART_ButtonOne", this) as Button;
Button buttonTwo = Template.FindName("PART_ButtonTwo", this) as Button;
Button buttonThree = Template.FindName("PART_ButtonThree", this) as Button;
Button buttonFour = Template.FindName("PART_ButtonFour", this) as Button;
Button buttonFive = Template.FindName("PART_ButtonFive", this) as Button;
Button buttonSix = Template.FindName("PART_ButtonSix", this) as Button;
Button buttonSeven = Template.FindName("PART_ButtonSeven", this) as Button;
Button buttonEight = Template.FindName("PART_ButtonEight", this) as Button;
Button buttonNine = Template.FindName("PART_ButtonNine", this) as Button;
enterButton.Click += new RoutedEventHandler(KeyPadButtonPressEventHandler);
cancelButton.Click += new RoutedEventHandler(KeyPadButtonPressEventHandler);
deleteButton.Click += new RoutedEventHandler(KeyPadButtonPressEventHandler);
decimalButton.Click += new RoutedEventHandler(KeyPadButtonPressEventHandler);
buttonOne.Click += new RoutedEventHandler(KeyPadButtonPressEventHandler);
buttonTwo.Click += new RoutedEventHandler(KeyPadButtonPressEventHandler);
buttonThree.Click += new RoutedEventHandler(KeyPadButtonPressEventHandler);
buttonFour.Click += new RoutedEventHandler(KeyPadButtonPressEventHandler);
buttonFive.Click += new RoutedEventHandler(KeyPadButtonPressEventHandler);
buttonSix.Click += new RoutedEventHandler(KeyPadButtonPressEventHandler);
buttonSeven.Click += new RoutedEventHandler(KeyPadButtonPressEventHandler);
buttonEight.Click += new RoutedEventHandler(KeyPadButtonPressEventHandler);
buttonNine.Click += new RoutedEventHandler(KeyPadButtonPressEventHandler);
优点:
缺点:
方法2:
我可以为generic.xaml文件创建代码隐藏。这将使我能够连接xaml中的事件处理程序,因为generic.xaml文件现在知道在哪里可以找到事件处理程序:
<Button x:Name="buttonThree" Style="{StaticResource ResourceKey=Buttons}"
Click="KeyPadButtonPressEventHandler" Content="3" />
在Generic.xaml.cs文件中:
namespace KeyPad
{
partial class Generic : ResourceDictionary
{
private void KeyPadButtonPressEventHandler(object sender, RoutedEventArgs e)
{
//Event handler logic here
}
}
}
优点:
缺点:
答案 0 :(得分:0)
我会在Control本身内部保留任何自定义控制逻辑。
请记住,generic.xaml仅用于定义Control的外观,使主题更容易。
您可以轻松覆盖您在generic.xaml中定义的样式。