我编写了一个自定义模板控件,其中包含一个按钮:
<ControlTemplate TargetType="local:IncrementalFlipView">
<Border
Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<StackPanel Orientation="Horizontal" Grid.Row="1" HorizontalAlignment="Center">
<Button Content="^" x:Name="PreviousPageButton" Click="Button_Click"/>
<TextBlock Text="1" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="10,0" FontSize="16" />
<Button Content="v" x:Name="NextPageButton"/>
</StackPanel>
</Border>
</ControlTemplate>
我的问题是,我不知道如何对按钮的单击事件做出反应。我Button_Click(object sender, RoutedEventArgs e)
在模板控件的代码中实现了一个事件处理程序,但未捕获按钮的click事件。
public sealed class IncrementalFlipView : Control
{
public IncrementalFlipView()
{
this.DefaultStyleKey = typeof(IncrementalFlipView);
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Debug.WriteLine("Clicked!");
}
}
知道如何应对该点击事件吗?
正确的方法(我的观点)是使用Command Bindings
。您的模板化控件中的样式化按钮将如下所示:
<Button Command="{Binding DataContext.BackCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type YourUIType}}}" CommandParameter="{Binding}" />
您的类型AncestorType
取决于您使用的UI元素。
在主窗口中,您应该定义Command
:
private RelayCommand _backCommand;
public ICommand BackCommand
{
get { return _backCommand ?? (_backCommand = new RelayCommand(Back)); }
}
如果您通过Internet访问,则将看到RelayCommand
该ICommand
接口的基本定义(请参见[here])。1个
然后,您只需要定义该Back
方法(它具有一个paramethrized对象):
private void Back(object obj)
{
// Go back command
...
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句