簡體   English   中英

具有自定義控件的簡單WPF事件問題

[英]Simple WPF event question with custom control

我制作了一個名為“ ShardButton”的自定義按鈕,該按鈕使用一種樣式來控制其內容以及事件觸發器:

<Style x:Key="ButtonStyle" TargetType="{x:Type obj:ShardButton}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type obj:ShardButton}">
                <Grid>
                    <Path .../>
                    <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" 
                                      VerticalAlignment="{TemplateBinding VerticalContentAlignment}" 
                                      SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" 
                                      RecognizesAccessKey="True"/>
                </Grid>
                <ControlTemplate.Triggers>
                    <EventTrigger RoutedEvent="ButtonBase.Click">
                        !!!SOMETHING HERE!!!
                    </EventTrigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

我在主Window1.xaml文件中使用上述XAML,並為“ obj”命名空間創建了一個xmlns,所以我想做的是在ShardButton類上調用自定義事件處理方法,我該如何在XAML中做到這一點?

我似乎找不到為Google搜索表達其用語的正確方法。

感謝你給與我的幫助!

標記

您不能直接在EventTriggers中執行事件處理程序,因為它們不是為此目的而創建的。

但是,如果您的ShardButton的每個實例都必須在單擊時執行相同的操作,則只需覆蓋ShardButton類中的OnClick方法,然后執行此處要做的任何事情。

如果您不希望這種行為,而是希望為每個使用Window1.xaml中定義的特定樣式的ShardButton實例執行特定的處理程序,請添加另一個設置器:

<Setter Property="Command" Value="{Binding RelativeSource={RelativeSource AncestorType={x:Type obj:Window1}}, Path=MyCommand}" />

其中MyCommand是Window1的實例屬性,它返回ICommand的自定義實現,該實現將調用您的處理程序。 此行代碼假定使用此樣式的每個按鈕都在Window1的可視樹中的某個位置,這可能是這種情況(否則樣式將在其他位置定義)。

您可以在自己的Style使用EventSetter

<Style ...>
    <EventSetter Event="Click" Handler="yourHandlerMethod"/>
</Style>

然后在您的代碼背后:

private void yourHandlerMethod(object sender, RoutedEventArgs e)
{
    ...
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM